// Live Chat Widget - Responsive Across All Devices
// Fallback script (main logic is in responsive-chat-ai.js)

function initLiveChat() {
    document.addEventListener('DOMContentLoaded', function() {
        // Chat Elements
        const chatToggleBtn = document.getElementById('chatToggleBtn');
        const chatCloseBtn = document.getElementById('chatCloseBtn');
        const chatBox = document.getElementById('chatBox');
        const chatInput = document.getElementById('chatInput');
        const chatSendBtn = document.getElementById('chatSendBtn');
        const chatMessages = document.getElementById('chatMessages');
        const chatBadge = document.getElementById('chatBadge');

        // Return if elements don't exist
        if (!chatToggleBtn || !chatBox) return;

        let messageCount = 0;

        // AI Chat Responses
        const aiResponses = [
            "What specific service are you interested in?",
            "Our interior design services include residential, commercial, and consultation packages.",
            "Would you like more details about our design process?",
            "We offer free initial consultation. Shall I schedule one for you?",
            "Tell me about your space and we'll create the perfect design for you!",
            "Tell me about your project vision!",
            "What's the scope of your interior design project?",
            "How can I help with your order?",
            "Thank you for reaching out!",
            "How can our team assist you?",
            "Would you prefer email, phone, or meeting?",
            "We'll respond within 24 hours. What's your preferred contact method?",
            "You can also reach us at support@faren.com or call us anytime!"
        ];

        // Toggle Chat Box
        if (chatToggleBtn) {
            chatToggleBtn.addEventListener('click', function() {
                chatBox.classList.toggle('active');
                if (chatBox.classList.contains('active')) {
                    if (window.innerWidth <= 480) document.body.style.overflow = 'hidden';
                    if (chatInput) chatInput.focus();
                    if (chatBadge) chatBadge.style.display = 'none';
                }
            });
        }

        // Close Chat Box
        if (chatCloseBtn) {
            chatCloseBtn.addEventListener('click', function() {
                chatBox.classList.remove('active');
                document.body.style.overflow = '';
            });
        }

        // Close with Escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && chatBox.classList.contains('active')) {
                chatBox.classList.remove('active');
                document.body.style.overflow = '';
            }
        });

        // Add User Message
        function addUserMessage(text) {
            const now = new Date();
            const timeStr = now.toLocaleTimeString('en-US', { 
                hour: '2-digit', 
                minute: '2-digit',
                hour12: true 
            });

            const messageDiv = document.createElement('div');
            messageDiv.className = 'chat-message user';
            messageDiv.innerHTML = `
                <div>
                    <div class="message-bubble user">${escapeHtml(text)}</div>
                    <div class="chat-timestamp">${timeStr}</div>
                </div>
            `;
            if (chatMessages) {
                chatMessages.appendChild(messageDiv);
                scrollToBottom();
            }
        }

        // Add Bot Message
        function addBotMessage(text) {
            const now = new Date();
            const timeStr = now.toLocaleTimeString('en-US', { 
                hour: '2-digit', 
                minute: '2-digit',
                hour12: true 
            });

            const messageDiv = document.createElement('div');
            messageDiv.className = 'chat-message';
            messageDiv.innerHTML = `
                <div>
                    <div class="message-bubble bot">${text}</div>
                    <div class="chat-timestamp">${timeStr}</div>
                </div>
            `;
            if (chatMessages) {
                chatMessages.appendChild(messageDiv);
                scrollToBottom();
            }
        }

        // Send Message Handler
        function sendMessage() {
            if (!chatInput) return;
            const message = chatInput.value.trim();
            if (!message) return;

            // Add user message
            addUserMessage(message);
            chatInput.value = '';
            chatInput.style.height = 'auto';

            // Simulate bot response delay
            setTimeout(() => {
                const randomResponse = aiResponses[Math.floor(Math.random() * aiResponses.length)];
                addBotMessage(randomResponse);
            }, 800);

            messageCount++;
        }

        // Scroll to Bottom
        function scrollToBottom() {
            setTimeout(() => {
                if (chatMessages) {
                    chatMessages.scrollTop = chatMessages.scrollHeight;
                }
            }, 0);
        }

        // Escape HTML
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // Send Button Click
        if (chatSendBtn) {
            chatSendBtn.addEventListener('click', sendMessage);
        }

        // Enter Key to Send (Shift+Enter for new line)
        if (chatInput) {
            chatInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });

            // Auto-resize Textarea
            chatInput.addEventListener('input', function() {
                this.style.height = 'auto';
                this.style.height = Math.min(this.scrollHeight, 100) + 'px';
            });
        }

        // Show notification badge when message arrives (demo)
        window.addEventListener('blur', () => {
            if (messageCount > 0 && !chatBox.classList.contains('active')) {
                if (chatBadge) chatBadge.style.display = 'flex';
            }
        });
    });
}

// Auto-initialize on page load
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initLiveChat);
} else {
    initLiveChat();
}
