// Builder Bee Chat System - FIXED VERSION with Proper Scrolling
// This version ensures the input field NEVER disappears

class BuilderBeeChat {
    constructor() {
        this.isOpen = false;
        this.messages = [];
        this.webhookUrl = 'https://builderbeeprojects.webhook.office.com/webhookb2/your-webhook-url';
        this.init();
    }

    init() {
        this.createChatWidget();
        this.bindEvents();
        console.log('Builder Bee Chat System - FIXED VERSION initialized 🐝');
    }

    createChatWidget() {
        // Remove any existing chat widget
        const existing = document.getElementById('intercom-container');
        if (existing) {
            existing.remove();
        }

        // Create the chat widget HTML with proper structure
        const chatHTML = `
            <div id="intercom-container" class="intercom-namespace">
                <div id="intercom-frame" class="intercom-frame">
                    <div class="intercom-messenger-frame">
                        <div class="intercom-messenger">
                            <div class="intercom-messenger-header">
                                <div class="intercom-messenger-header-content">
                                    <div class="intercom-avatar">
                                        <span class="bee-icon">🐝</span>
                                    </div>
                                    <div class="intercom-header-text">
                                        <h3 class="intercom-header-title">Builder Bee Assistant</h3>
                                        <p class="intercom-header-subtitle">We're here to help with your project!</p>
                                    </div>
                                    <button class="intercom-close-button" onclick="builderBeeChat.closeChat()">×</button>
                                </div>
                            </div>
                            <div class="intercom-messenger-body">
                                <div class="intercom-conversation" id="chat-conversation">
                                    <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>
                                </div>
                                <div class="intercom-composer" id="chat-composer">
                                    <div class="intercom-composer-input-wrapper">
                                        <textarea 
                                            class="intercom-composer-textarea" 
                                            id="chat-input"
                                            placeholder="Type your message..."
                                            rows="1"
                                        ></textarea>
                                        <button class="intercom-composer-send-button" id="chat-send-btn">
                                            <span>➤</span>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="intercom-launcher" id="chat-launcher">
                    <div class="intercom-launcher-badge">1</div>
                    <div class="intercom-launcher-icon">💬</div>
                </div>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', chatHTML);
        
        // Add initial message to messages array
        this.messages.push({
            sender: 'admin',
            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?",
            timestamp: new Date()
        });
    }

    bindEvents() {
        // Chat launcher click
        document.getElementById('chat-launcher').addEventListener('click', () => {
            this.toggleChat();
        });

        // Send button click
        document.getElementById('chat-send-btn').addEventListener('click', () => {
            this.sendMessage();
        });

        // Enter key press
        document.getElementById('chat-input').addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessage();
            }
        });

        // Auto-resize textarea
        document.getElementById('chat-input').addEventListener('input', (e) => {
            this.autoResizeTextarea(e.target);
        });
    }

    toggleChat() {
        const frame = document.getElementById('intercom-frame');
        const launcher = document.getElementById('chat-launcher');
        
        if (this.isOpen) {
            this.closeChat();
        } else {
            this.openChat();
        }
    }

    openChat() {
        const frame = document.getElementById('intercom-frame');
        const launcher = document.getElementById('chat-launcher');
        
        frame.classList.add('active');
        launcher.style.display = 'none';
        this.isOpen = true;
        
        // Scroll to bottom after opening
        setTimeout(() => {
            this.scrollToBottom();
        }, 100);
        
        // Log event
        console.log('Chat Event: chat_opened', {});
    }

    closeChat() {
        const frame = document.getElementById('intercom-frame');
        const launcher = document.getElementById('chat-launcher');
        
        frame.classList.remove('active');
        launcher.style.display = 'flex';
        this.isOpen = false;
        
        // Log event
        console.log('Chat Event: chat_closed', {});
    }

    sendMessage() {
        const input = document.getElementById('chat-input');
        const message = input.value.trim();
        
        if (!message) return;
        
        // Add user message
        this.addMessage('user', message);
        
        // Clear input
        input.value = '';
        this.autoResizeTextarea(input);
        
        // Send to webhook (simulate response)
        this.sendToWebhook(message);
        
        // Log event
        console.log('Chat Event: message_sent', {
            sender: 'user',
            messageLength: message.length
        });
    }

    addMessage(sender, text) {
        const conversation = document.getElementById('chat-conversation');
        const messageData = {
            sender: sender,
            text: text,
            timestamp: new Date()
        };
        
        this.messages.push(messageData);
        
        const messageHTML = `
            <div class="intercom-comment intercom-comment-from-${sender}">
                <div class="intercom-comment-body">
                    <div class="intercom-comment-text">${text}</div>
                </div>
            </div>
        `;
        
        conversation.insertAdjacentHTML('beforeend', messageHTML);
        
        // Always scroll to bottom after adding message
        this.scrollToBottom();
    }

    scrollToBottom() {
        const conversation = document.getElementById('chat-conversation');
        if (conversation) {
            // Use smooth scrolling to bottom
            conversation.scrollTo({
                top: conversation.scrollHeight,
                behavior: 'smooth'
            });
        }
    }

    autoResizeTextarea(textarea) {
        textarea.style.height = 'auto';
        textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px';
    }

    async sendToWebhook(message) {
        // Simulate admin response after delay
        setTimeout(() => {
            let response = this.generateResponse(message);
            this.addMessage('admin', response);
            
            // Log admin response
            console.log('Chat Event: message_sent', {
                sender: 'admin',
                messageLength: response.length
            });
        }, 1000 + Math.random() * 2000);

        // Try to send to actual webhook (optional)
        try {
            const payload = {
                message: message,
                timestamp: new Date().toISOString(),
                source: 'BuilderBee Website Chat'
            };
            
            // Uncomment when you have actual webhook URL
            // await fetch(this.webhookUrl, {
            //     method: 'POST',
            //     headers: { 'Content-Type': 'application/json' },
            //     body: JSON.stringify(payload)
            // });
        } catch (error) {
            console.log('Webhook send failed (using fallback responses):', error);
        }
    }

    generateResponse(message) {
        const responses = [
            "Thanks for reaching out! 😊 I'd love to help you with your project. Can you tell me more about what you have in mind?",
            "That sounds like an exciting project! We have extensive experience with that type of work. What's your timeline looking like?",
            "Great question! Our team would be happy to provide you with a detailed quote. Can you share more specifics about your project requirements?",
            "We've completed many similar projects in North Carolina. I'd recommend scheduling a free consultation so we can discuss your vision in detail.",
            "Excellent! That's definitely something we can help with. Our 25+ years of experience makes us perfect for this type of project. When would you like to get started?",
            "Perfect! We love working on projects like this. Let me connect you with our project manager who can provide you with detailed information and pricing.",
            "That's a fantastic idea! We've done many similar renovations and the results are always amazing. Would you like to see some examples of our recent work?",
            "Absolutely! We're licensed and insured for all types of construction work. I can have our team prepare a comprehensive proposal for you."
        ];
        
        return responses[Math.floor(Math.random() * responses.length)];
    }
}

// Initialize the chat system when DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    window.builderBeeChat = new BuilderBeeChat();
});

// Also initialize if DOM is already loaded
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function() {
        window.builderBeeChat = new BuilderBeeChat();
    });
} else {
    window.builderBeeChat = new BuilderBeeChat();
}

