// Advanced Chat System with n8n Integration
// Inspired by Blotato.com's sophisticated messaging architecture

class BuilderBeeChat {
    constructor() {
        this.webhookUrl = 'https://builderbee.app.n8n.cloud/webhook/f406671e-c954-4691-b39a-66c90aa2f103/chat';
        this.conversationHistory = [];
        this.isTyping = false;
        this.messageQueue = [];
        this.sessionId = this.generateSessionId();
        this.isInitialized = false;
        
        this.init();
    }

    generateSessionId() {
        return 'bb_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }

    init() {
        if (this.isInitialized) return;
        
        this.setupEventListeners();
        this.setupKeyboardShortcuts();
        this.loadConversationHistory();
        this.isInitialized = true;
        
        console.log('Builder Bee Chat System initialized 🐝');
    }

    setupEventListeners() {
        // Chat launcher
        const launcher = document.getElementById('intercom-launcher');
        if (launcher) {
            launcher.addEventListener('click', () => this.toggleChat());
        }

        // Close button
        const closeButton = document.getElementById('close-chat');
        if (closeButton) {
            closeButton.addEventListener('click', () => this.closeChat());
        }

        // Send button
        const sendButton = document.getElementById('send-message');
        if (sendButton) {
            sendButton.addEventListener('click', () => this.handleSendMessage());
        }

        // Input field
        const input = document.getElementById('chat-input');
        if (input) {
            input.addEventListener('keydown', (e) => this.handleKeyDown(e));
            input.addEventListener('input', () => this.autoResizeInput());
            input.addEventListener('paste', (e) => this.handlePaste(e));
        }

        // Click outside to close
        document.addEventListener('click', (e) => {
            const chatContainer = document.getElementById('intercom-container');
            if (chatContainer && !chatContainer.contains(e.target)) {
                // Don't close if clicking on elements that should open chat
                if (!e.target.closest('.cta-button, .service-btn, .nav-link')) {
                    this.closeChat();
                }
            }
        });
    }

    setupKeyboardShortcuts() {
        document.addEventListener('keydown', (e) => {
            // Ctrl/Cmd + K to open chat
            if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
                e.preventDefault();
                this.openChat();
                document.getElementById('chat-input')?.focus();
            }
            
            // Escape to close chat
            if (e.key === 'Escape') {
                this.closeChat();
            }
        });
    }

    toggleChat() {
        const frame = document.getElementById('intercom-frame');
        if (frame && frame.classList.contains('active')) {
            this.closeChat();
        } else {
            this.openChat();
        }
    }

    openChat() {
        const frame = document.getElementById('intercom-frame');
        const badge = document.getElementById('chat-badge');
        
        if (frame) {
            frame.classList.add('active');
            setTimeout(() => {
                document.getElementById('chat-input')?.focus();
            }, 300);
        }
        
        if (badge) {
            badge.style.display = 'none';
        }

        // Track chat open event
        this.trackEvent('chat_opened');
    }

    closeChat() {
        const frame = document.getElementById('intercom-frame');
        if (frame) {
            frame.classList.remove('active');
        }
    }

    handleKeyDown(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            this.handleSendMessage();
        }
    }

    handlePaste(e) {
        // Handle pasted content
        setTimeout(() => {
            this.autoResizeInput();
        }, 0);
    }

    autoResizeInput() {
        const input = document.getElementById('chat-input');
        if (input) {
            input.style.height = 'auto';
            input.style.height = Math.min(input.scrollHeight, 100) + 'px';
        }
    }

    async handleSendMessage() {
        const input = document.getElementById('chat-input');
        const sendButton = document.getElementById('send-message');
        
        if (!input || !input.value.trim()) return;

        const message = input.value.trim();
        input.value = '';
        this.autoResizeInput();

        // Disable send button temporarily
        if (sendButton) {
            sendButton.disabled = true;
        }

        // Add user message to chat
        this.addMessage('user', message);

        // Show typing indicator
        this.showTypingIndicator();

        try {
            // Send to n8n webhook
            const response = await this.sendToWebhook(message);
            
            // Hide typing indicator
            this.hideTypingIndicator();
            
            // Add AI response
            if (response && response.message) {
                this.addMessage('admin', response.message);
            } else {
                this.addMessage('admin', this.getFallbackResponse(message));
            }
        } catch (error) {
            console.error('Chat error:', error);
            this.hideTypingIndicator();
            this.addMessage('admin', this.getErrorResponse());
        } finally {
            // Re-enable send button
            if (sendButton) {
                sendButton.disabled = false;
            }
        }
    }

    async sendToWebhook(message) {
        const payload = {
            message: message,
            sessionId: this.sessionId,
            timestamp: new Date().toISOString(),
            conversationHistory: this.conversationHistory.slice(-5), // Last 5 messages for context
            userAgent: navigator.userAgent,
            referrer: document.referrer,
            currentPage: window.location.href
        };

        const response = await fetch(this.webhookUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(payload)
        });

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

        return await response.json();
    }

    addMessage(sender, text, options = {}) {
        const messagesContainer = document.getElementById('chat-messages');
        if (!messagesContainer) return;

        const messageElement = document.createElement('div');
        messageElement.className = `intercom-comment intercom-comment-from-${sender}`;
        
        const messageBody = document.createElement('div');
        messageBody.className = 'intercom-comment-body';
        
        const messageText = document.createElement('div');
        messageText.className = 'intercom-comment-text';
        messageText.textContent = text;
        
        messageBody.appendChild(messageText);
        messageElement.appendChild(messageBody);
        
        // Add timestamp if needed
        if (options.showTimestamp) {
            const timestamp = document.createElement('div');
            timestamp.className = 'intercom-comment-timestamp';
            timestamp.textContent = new Date().toLocaleTimeString();
            messageBody.appendChild(timestamp);
        }
        
        messagesContainer.appendChild(messageElement);
        
        // Scroll to bottom
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
        
        // Add to conversation history
        this.conversationHistory.push({
            sender: sender,
            message: text,
            timestamp: new Date().toISOString()
        });
        
        // Save to localStorage
        this.saveConversationHistory();
        
        // Track message event
        this.trackEvent('message_sent', { sender, messageLength: text.length });
    }

    showTypingIndicator() {
        if (this.isTyping) return;
        
        this.isTyping = true;
        const messagesContainer = document.getElementById('chat-messages');
        if (!messagesContainer) return;

        const typingElement = document.createElement('div');
        typingElement.id = 'typing-indicator';
        typingElement.className = 'typing-indicator';
        typingElement.innerHTML = `
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
        `;
        
        messagesContainer.appendChild(typingElement);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    hideTypingIndicator() {
        this.isTyping = false;
        const typingElement = document.getElementById('typing-indicator');
        if (typingElement) {
            typingElement.remove();
        }
    }

    getFallbackResponse(userMessage) {
        const message = userMessage.toLowerCase();
        
        // Construction-related keywords
        if (message.includes('kitchen') || message.includes('cook')) {
            return "I'd love to help you with your kitchen renovation! Our team specializes in custom kitchen designs with premium materials. We can discuss cabinet installation, countertops, plumbing, electrical work, and more. What specific aspects of your kitchen are you looking to update?";
        }
        
        if (message.includes('bathroom') || message.includes('bath')) {
            return "Bathroom renovations are one of our specialties! We create beautiful, functional spaces with luxury fixtures and modern designs. Are you thinking about a complete remodel or specific updates like tile work, vanities, or shower installations?";
        }
        
        if (message.includes('addition') || message.includes('expand') || message.includes('room')) {
            return "Home additions are a great way to expand your living space! We handle everything from room extensions to second-story additions. Our team ensures seamless integration with your existing home. What type of addition are you considering?";
        }
        
        if (message.includes('new') && (message.includes('home') || message.includes('house') || message.includes('build'))) {
            return "Building a new home is exciting! We provide comprehensive construction services from foundation to finishing. Our team handles custom home construction with attention to every detail. Do you have plans already, or would you like to discuss design options?";
        }
        
        if (message.includes('quote') || message.includes('cost') || message.includes('price') || message.includes('estimate')) {
            return "I'd be happy to help you get a free quote! To provide an accurate estimate, I'll need some details about your project. Could you tell me: 1) What type of work you're considering, 2) The approximate size/scope, and 3) Your timeline? You can also call us at (252) 689-0660 for immediate assistance.";
        }
        
        if (message.includes('timeline') || message.includes('how long') || message.includes('when')) {
            return "Project timelines vary depending on the scope of work. Kitchen renovations typically take 2-4 weeks, bathroom remodels 1-3 weeks, and home additions 6-12 weeks. We'll provide a detailed timeline with your quote. What type of project are you planning?";
        }
        
        if (message.includes('experience') || message.includes('years') || message.includes('qualified')) {
            return "Builder Bee Projects has over 25 years of experience in construction and renovation across North Carolina. We've completed 500+ projects with 100% customer satisfaction. Our team is fully licensed, insured, and committed to quality craftsmanship. What questions do you have about our services?";
        }
        
        if (message.includes('area') || message.includes('location') || message.includes('service')) {
            return "We proudly serve Raleigh, Durham, Chapel Hill, and surrounding areas throughout North Carolina. Our team travels throughout the region for projects. What's your location, and what type of project are you considering?";
        }
        
        // General responses
        const generalResponses = [
            "Thank you for your interest in Builder Bee Projects! With 25+ years of experience, we specialize in kitchen renovations, bathroom remodels, home additions, and new construction. How can I help you with your project today?",
            "I'm here to help you with your construction and renovation needs! Whether you're planning a kitchen update, bathroom remodel, home addition, or new build, our experienced team can bring your vision to life. What project are you considering?",
            "Great to hear from you! Builder Bee Projects has been North Carolina's trusted contractor for over 25 years. We handle everything from small renovations to complete home construction. What type of project can we help you with?"
        ];
        
        return generalResponses[Math.floor(Math.random() * generalResponses.length)];
    }

    getErrorResponse() {
        return "I apologize, but I'm having trouble connecting right now. Please call us directly at (252) 689-0660 or email info@builderbeeprojects.com, and we'll be happy to help you with your project immediately!";
    }

    saveConversationHistory() {
        try {
            localStorage.setItem('builderBeeChat_history', JSON.stringify(this.conversationHistory));
            localStorage.setItem('builderBeeChat_sessionId', this.sessionId);
        } catch (error) {
            console.warn('Could not save chat history:', error);
        }
    }

    loadConversationHistory() {
        try {
            const savedHistory = localStorage.getItem('builderBeeChat_history');
            const savedSessionId = localStorage.getItem('builderBeeChat_sessionId');
            
            if (savedHistory) {
                this.conversationHistory = JSON.parse(savedHistory);
            }
            
            if (savedSessionId) {
                this.sessionId = savedSessionId;
            }
        } catch (error) {
            console.warn('Could not load chat history:', error);
        }
    }

    trackEvent(eventName, data = {}) {
        // Analytics tracking
        if (typeof gtag !== 'undefined') {
            gtag('event', eventName, {
                event_category: 'chat',
                event_label: 'builder_bee_chat',
                ...data
            });
        }
        
        console.log('Chat Event:', eventName, data);
    }

    // Public API methods
    sendMessage(message) {
        this.addMessage('admin', message);
    }

    clearHistory() {
        this.conversationHistory = [];
        this.saveConversationHistory();
        
        const messagesContainer = document.getElementById('chat-messages');
        if (messagesContainer) {
            messagesContainer.innerHTML = `
                <div class="intercom-comment intercom-comment-from-admin">
                    <div class="intercom-comment-body">
                        <div class="intercom-comment-text">
                            Hi! I'm your Builder Bee assistant. I can help you with information about our construction and renovation services. What project are you considering?
                        </div>
                    </div>
                </div>
            `;
        }
    }

    getSessionInfo() {
        return {
            sessionId: this.sessionId,
            messageCount: this.conversationHistory.length,
            startTime: this.conversationHistory[0]?.timestamp,
            lastActivity: this.conversationHistory[this.conversationHistory.length - 1]?.timestamp
        };
    }
}

// Initialize chat system when DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    // Create global chat manager
    window.chatManager = new BuilderBeeChat();
    
    // Expose global functions for backward compatibility
    window.openChat = () => window.chatManager.openChat();
    window.closeChat = () => window.chatManager.closeChat();
    window.addMessage = (sender, text) => window.chatManager.addMessage(sender, text);
    
    // Show notification badge after 30 seconds if no interaction
    setTimeout(() => {
        const badge = document.getElementById('chat-badge');
        const frame = document.getElementById('intercom-frame');
        
        if (badge && frame && !frame.classList.contains('active')) {
            badge.style.display = 'flex';
            badge.textContent = '1';
        }
    }, 30000);
    
    console.log('Builder Bee Chat System ready! 💬');
});

// Handle page visibility changes
document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        // Page is hidden, save state
        if (window.chatManager) {
            window.chatManager.saveConversationHistory();
        }
    } else {
        // Page is visible, restore focus if chat is open
        const frame = document.getElementById('intercom-frame');
        if (frame && frame.classList.contains('active')) {
            setTimeout(() => {
                document.getElementById('chat-input')?.focus();
            }, 100);
        }
    }
});

// Handle beforeunload to save chat state
window.addEventListener('beforeunload', function() {
    if (window.chatManager) {
        window.chatManager.saveConversationHistory();
    }
});

