class AvisionChatbot {
    constructor() {
        this.isOpen = false;
        this.messages = [];
        this.suggestions = ['reviews', 'posts', 'future', 'competitor'];
    }

    init() {
        this.container = document.querySelector('.chatbot-widget');
        if (!this.container) return;

        this.window = this.container.querySelector('.chatbot-window');
        this.messagesContainer = this.container.querySelector('.chatbot-messages');
        this.input = this.container.querySelector('.chatbot-input input');
        this.sendBtn = this.container.querySelector('.chatbot-input button');
        
        this.setupEventListeners();
        this.loadHistory();
        if (this.messages.length === 0) {
            this.addBotMessage(this.getNeutralPlaceholder());
        }
    }

    getNeutralPlaceholder() {
        return (typeof window.avisionI18n !== 'undefined' && window.avisionI18n.get('chat_connecting'))
            ? window.avisionI18n.get('chat_connecting')
            : 'Connexion à AVI...';
    }

    setupEventListeners() {
        const toggleBtn = this.container.querySelector('.chatbot-toggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', () => this.toggle());
        }

        const closeBtn = this.container.querySelector('.chatbot-close');
        if (closeBtn) {
            closeBtn.addEventListener('click', () => this.close());
        }

        if (this.sendBtn) {
            this.sendBtn.addEventListener('click', () => this.sendMessage());
        }

        if (this.input) {
            this.input.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    this.sendMessage();
                }
            });
        }

        this.container.querySelectorAll('.chip').forEach(chip => {
            chip.addEventListener('click', () => {
                const topic = chip.dataset.topic;
                this.handleSuggestion(topic);
            });
        });
    }

    toggle() {
        if (this.isOpen) {
            this.close();
        } else {
            this.open();
        }
    }

    open() {
        this.isOpen = true;
        this.window.classList.add('open');
        this.input?.focus();
        this.scrollToBottom();
        
        const dot = this.container.querySelector('.notification-dot');
        if (dot) dot.style.display = 'none';
    }

    close() {
        this.isOpen = false;
        this.window.classList.remove('open');
    }

    sendMessage() {
        const text = this.input?.value?.trim();
        if (!text) return;

        this.addUserMessage(text);
        this.input.value = '';
        this.showTyping();
        this.callChatAPI(text);
    }

    callChatAPI(message) {
        const self = this;
        const ajaxUrl = (typeof avisionSettings !== 'undefined' && avisionSettings.ajaxUrl) ? avisionSettings.ajaxUrl : (window.avisionSettings && window.avisionSettings.ajaxUrl) || '/wp-admin/admin-ajax.php';
        const formData = new FormData();
        formData.append('action', 'avision_api');
        formData.append('avision_action', 'send_chat_message');
        formData.append('message', message);
        formData.append('currentLevel', 1);
        formData.append('score', 0);
        if (typeof avisionSettings !== 'undefined' && avisionSettings.nonce) formData.append('nonce', avisionSettings.nonce);
        else if (window.avisionSettings && window.avisionSettings.nonce) formData.append('nonce', window.avisionSettings.nonce);

        fetch(ajaxUrl, { method: 'POST', body: formData })
            .then(r => r.json())
            .then(resp => {
                self.hideTyping();
                const data = resp && resp.data ? resp.data : resp;
                const reply = (resp && resp.success && data && data.reply) ? data.reply : (self.getNeutralPlaceholder() + ' (erreur)');
                self.addBotMessage(reply);
            })
            .catch(() => {
                self.hideTyping();
                self.addBotMessage(self.getNeutralPlaceholder() + ' Réessayez.');
            });
    }

    addUserMessage(text) {
        this.messages.push({ sender: 'user', text, timestamp: Date.now() });
        this.renderMessage('user', text);
        this.saveHistory();
    }

    addBotMessage(text) {
        this.messages.push({ sender: 'bot', text, timestamp: Date.now() });
        this.renderMessage('bot', text);
        this.saveHistory();
    }

    renderMessage(sender, text) {
        const msgEl = document.createElement('div');
        msgEl.className = `message ${sender}`;
        // Réponses AVI : HTML de confiance (FastAPI / span.avi-text-orange) — ne pas passer par textContent.
        if (sender === 'bot') {
            msgEl.style.whiteSpace = 'normal';
            msgEl.innerHTML = typeof text === 'string' ? text : '';
        } else {
            msgEl.textContent = text;
        }
        
        const typingEl = this.messagesContainer?.querySelector('.message.typing');
        if (typingEl) {
            this.messagesContainer.insertBefore(msgEl, typingEl);
        } else {
            this.messagesContainer?.appendChild(msgEl);
        }
        
        this.scrollToBottom();
    }

    showTyping() {
        const typingEl = document.createElement('div');
        typingEl.className = 'message bot typing';
        typingEl.innerHTML = `
            <div class="typing-indicator">
                <span></span><span></span><span></span>
            </div>
        `;
        this.messagesContainer?.appendChild(typingEl);
        this.scrollToBottom();
    }

    hideTyping() {
        const typingEl = this.messagesContainer?.querySelector('.message.typing');
        if (typingEl) {
            typingEl.remove();
        }
    }

    handleSuggestion(topic) {
        const topicMessages = {
            'reviews': window.avisionI18n.get('chatbot_suggestion_reviews', 'Tell me about reviews'),
            'posts': window.avisionI18n.get('chatbot_suggestion_posts', 'How do Google Posts work?'),
            'future': window.avisionI18n.get('chatbot_suggestion_future', 'What features are coming?'),
            'competitor': window.avisionI18n.get('chatbot_suggestion_competitor', 'How do I compare to competitors?')
        };

        const message = topicMessages[topic] || topic;
        this.input.value = message;
        this.sendMessage();
    }

    scrollToBottom() {
        if (this.messagesContainer) {
            this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
        }
    }

    loadHistory() {
        const saved = localStorage.getItem('avision_chat_history');
        if (!saved) return;
        try {
            const list = JSON.parse(saved);
            if (!Array.isArray(list)) return;
            const hasObsolete = list.some(msg => {
                const text = (msg && (msg.text || msg.message || '')) + '';
                return text.indexOf('Catégorie Principale') !== -1 || text.indexOf('Ravi de te revoir') !== -1;
            });
            if (hasObsolete) {
                localStorage.removeItem('avision_chat_history');
                return;
            }
            this.messages = list;
            this.messages.forEach(msg => {
                this.renderMessage(msg.sender, msg.text);
            });
        } catch (e) {
            console.error('Failed to load chat history:', e);
        }
    }

    saveHistory() {
        const recentMessages = this.messages.slice(-50);
        localStorage.setItem('avision_chat_history', JSON.stringify(recentMessages));
    }

    clearHistory() {
        this.messages = [];
        localStorage.removeItem('avision_chat_history');
        if (this.messagesContainer) {
            this.messagesContainer.innerHTML = '';
        }
    }
}

document.addEventListener('DOMContentLoaded', () => {
    window.avisionChatbot = new AvisionChatbot();
    window.avisionChatbot.init();
});
