/**
 * FAREN AI Live Chat Widget
 * Uses the PHP API when available and falls back to local demo mode.
 */

if (window.__FAREN_LIVE_CHAT_SCRIPT_LOADED__) {
    console.warn('FAREN live chat already loaded, skipping duplicate initialization.');
} else {
    window.__FAREN_LIVE_CHAT_SCRIPT_LOADED__ = true;

    class FArenLiveChat {
        constructor(options = {}) {
            this.options = {
                apiBase: options.apiBase || this.resolveApiBase(),
                maxMessageLength: options.maxMessageLength || 1000,
                responseTimeout: options.responseTimeout || 15000,
                enableTypingIndicator: options.enableTypingIndicator !== false,
                storageKey: 'faren_chat_session',
                messagesKey: 'faren_messages_general',
                retryAttempts: 1,
                retryDelay: 800
            };

            this.state = {
                sessionId: null,
                isConnected: false,
                isLoading: false,
                unreadCount: 0,
                useLocalMode: false
            };

            this.localResponses = [
                'Thank you for your interest. Our team specializes in residential and commercial interior design.',
                'We offer free initial consultations. Share your space details and we can guide you.',
                'Our services include space planning, furniture selection, color consulting, lighting design, and full project management.',
                'You can also contact us directly for bookings and consultation support.',
                'Our pricing depends on your space size, design scope, and material requirements.'
            ];

            this.elements = {};
            this.messageHistory = [];
            this.widgetRoot = null;
            this.hasBootstrappedConversation = false;

            this.init();
        }

        async init() {
            this.normalizeWidgetInstances();
            if (!this.cacheElements()) return;

            this.attachEventListeners();
            this.loadSession();
            await this.checkAIStatus();
            this.restoreMessages();
        }

        resolveApiBase() {
            const configuredMeta = document.querySelector('meta[name="faren-api-base"]');
            if (configuredMeta && configuredMeta.content) {
                return configuredMeta.content;
            }

            const script = document.currentScript
                || document.querySelector('script[src*="responsive-chat-ai.js"]');

            if (script && script.src) {
                try {
                    const scriptUrl = new URL(script.src, window.location.href);
                    const rootPath = scriptUrl.pathname.replace(/\/assets\/js\/responsive-chat-ai\.js$/, '');
                    return `${rootPath}/auth-system/api/chat-ai-v3.php`;
                } catch (error) {
                    console.warn('Unable to derive API path from script URL, falling back to pathname.');
                }
            }

            const pathSegments = window.location.pathname.split('/').filter(Boolean);
            if (pathSegments.length > 0) {
                return `/${pathSegments[0]}/auth-system/api/chat-ai-v3.php`;
            }

            return '/interior/auth-system/api/chat-ai-v3.php';
        }

        normalizeWidgetInstances() {
            const widgets = Array.from(document.querySelectorAll('.chat-widget-container'));
            if (!widgets.length) return;

            this.widgetRoot = widgets[widgets.length - 1];

            if (widgets.length > 1) {
                widgets.slice(0, -1).forEach((widget) => widget.remove());
            }
        }

        cacheElements() {
            this.widgetRoot = this.widgetRoot || document.querySelector('.chat-widget-container');
            if (!this.widgetRoot) {
                console.error('Chat widget container not found.');
                return false;
            }

            this.elements = {
                toggleBtn: this.widgetRoot.querySelector('#chatToggleBtn'),
                closeBtn: this.widgetRoot.querySelector('#chatCloseBtn'),
                chatBox: this.widgetRoot.querySelector('#chatBox'),
                messages: this.widgetRoot.querySelector('#chatMessages'),
                input: this.widgetRoot.querySelector('#chatInput'),
                sendBtn: this.widgetRoot.querySelector('#chatSendBtn'),
                statusSubtitle: this.widgetRoot.querySelector('#chatStatusSubtitle'),
                badge: this.widgetRoot.querySelector('#chatBadge')
            };

            return Boolean(this.elements.chatBox && this.elements.messages);
        }

        attachEventListeners() {
            if (this.elements.toggleBtn) {
                this.elements.toggleBtn.addEventListener('click', () => this.toggleChat());
                this.elements.toggleBtn.addEventListener('click', () => {
                    if (this.state.unreadCount > 0) {
                        this.state.unreadCount = 0;
                        this.updateBadge();
                    }
                });
            }

            if (this.elements.closeBtn) {
                this.elements.closeBtn.addEventListener('click', () => this.closeChat());
            }

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

            if (this.elements.input) {
                this.elements.input.addEventListener('keypress', (event) => {
                    if (event.key === 'Enter' && !event.shiftKey) {
                        event.preventDefault();
                        this.sendMessage();
                    }
                });

                this.elements.input.addEventListener('input', (event) => {
                    event.target.style.height = 'auto';
                    event.target.style.height = `${Math.min(event.target.scrollHeight, 100)}px`;
                });
            }

            document.addEventListener('keydown', (event) => {
                if (event.key === 'Escape' && this.elements.chatBox.classList.contains('active')) {
                    this.closeChat();
                }
            });

            window.addEventListener('online', () => this.handleOnline());
            window.addEventListener('offline', () => this.handleOffline());
        }

        toggleChat() {
            if (this.elements.chatBox.classList.contains('active')) {
                this.closeChat();
            } else {
                this.openChat();
            }
        }

        openChat() {
            this.elements.chatBox.classList.add('active');

            if (window.innerWidth <= 480) {
                document.body.style.overflow = 'hidden';
            }

            if (!this.state.sessionId && this.messageHistory.length === 0 && !this.hasBootstrappedConversation) {
                this.bootstrapConversation();
            }

            if (this.elements.input) {
                setTimeout(() => this.elements.input.focus(), 350);
            }
        }

        closeChat() {
            this.elements.chatBox.classList.remove('active');
            document.body.style.overflow = '';
        }

        async bootstrapConversation() {
            this.hasBootstrappedConversation = true;
            await this.startNewChat();

            if (this.messageHistory.length === 0 && this.state.useLocalMode) {
                this.addMessage('assistant', 'Live chat is not reachable on this server right now, so demo replies are active.');
            }
        }

        async startNewChat() {
            if (this.state.useLocalMode) {
                this.state.sessionId = `local_${Date.now()}`;
                this.state.isConnected = true;
                this.updateStatus('Local demo mode');
                this.saveSession();
                return;
            }

            try {
                const response = await this.makeRequest(`${this.options.apiBase}?action=start_chat`, {
                    method: 'POST',
                    body: JSON.stringify({
                        category: 'general',
                        user_email: this.getUserEmail()
                    })
                });

                if (!response.success) {
                    throw new Error(response.error || 'Failed to start chat');
                }

                this.state.sessionId = response.session_id;
                this.state.isConnected = true;
                this.updateStatus('Live AI connected');

                if (response.welcome_message) {
                    this.addMessage('assistant', response.welcome_message);
                }

                this.saveSession();
            } catch (error) {
                console.warn('API unavailable, switching to local mode:', error.message);
                this.switchToLocalMode();
            }
        }

        switchToLocalMode() {
            this.state.useLocalMode = true;
            this.state.sessionId = this.state.sessionId || `local_${Date.now()}`;
            this.state.isConnected = true;
            this.updateStatus('Local demo mode');
            this.saveSession();
        }

        getLocalResponse(message) {
            const msg = message.toLowerCase();

            if (msg.includes('price') || msg.includes('cost') || msg.includes('budget') || msg.includes('rate')) {
                return 'Our pricing depends on your space size, selected materials, and project scope. Share your requirements and we can guide you.';
            }
            if (msg.includes('consult') || msg.includes('appointment') || msg.includes('schedule') || msg.includes('book')) {
                return 'We offer free initial consultations. Visit the Consultation page or contact our team to schedule one.';
            }
            if (msg.includes('service') || msg.includes('offer')) {
                return 'We offer interior design, space planning, furniture selection, color consulting, and project execution support.';
            }
            if (msg.includes('project') || msg.includes('portfolio')) {
                return 'You can explore our Projects page to view completed residential and commercial work.';
            }
            if (msg.includes('contact') || msg.includes('email') || msg.includes('phone') || msg.includes('call')) {
                return 'You can reach our team directly through the Contact or Consultation page for faster support.';
            }
            if (msg.includes('hello') || msg.includes('hi') || msg.includes('hey')) {
                return 'Hello. How can I help you with your interior project today?';
            }

            return this.localResponses[Math.floor(Math.random() * this.localResponses.length)];
        }

        async sendMessage() {
            const message = this.elements.input ? this.elements.input.value.trim() : '';
            if (!message) return;

            if (message.length > this.options.maxMessageLength) {
                alert(`Message must be under ${this.options.maxMessageLength} characters.`);
                return;
            }

            if (!this.state.sessionId) {
                await this.startNewChat();
            }

            this.setLoading(true);
            this.addMessage('user', message);

            this.elements.input.value = '';
            this.elements.input.style.height = 'auto';

            if (this.options.enableTypingIndicator) {
                this.showTypingIndicator();
            }

            if (this.state.useLocalMode) {
                setTimeout(() => {
                    this.removeTypingIndicator();
                    this.addMessage('assistant', this.getLocalResponse(message));
                    this.setLoading(false);
                    this.saveSession();
                }, 700);
                return;
            }

            try {
                const response = await this.makeRequest(`${this.options.apiBase}?action=send_message`, {
                    method: 'POST',
                    body: JSON.stringify({
                        message: message,
                        category: 'general',
                        session_id: this.state.sessionId,
                        user_email: this.getUserEmail()
                    })
                });

                if (!response.success) {
                    throw new Error(response.error || 'Failed to send message');
                }

                this.removeTypingIndicator();
                this.addMessage('assistant', response.response);
                this.updateStatus('Live AI connected');
                this.saveSession();
            } catch (error) {
                console.warn('Live API failed, switching to local mode:', error.message);
                this.removeTypingIndicator();
                this.switchToLocalMode();
                this.addMessage('assistant', this.getLocalResponse(message));
            } finally {
                this.setLoading(false);
            }
        }

        addMessage(sender, 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 ${sender === 'user' ? 'user' : ''}`;
            messageDiv.innerHTML = `
                <div>
                    <div class="message-bubble ${sender === 'user' ? 'user' : 'bot'}">${this.escapeHtml(text)}</div>
                    <div class="chat-timestamp">${timeStr}</div>
                </div>
            `;

            this.elements.messages.appendChild(messageDiv);
            this.messageHistory.push({ sender, text, time: now.toISOString() });
            this.scrollToBottom();
            this.saveMessages();
        }

        showTypingIndicator() {
            const typingDiv = document.createElement('div');
            typingDiv.className = 'chat-message typing-indicator';
            typingDiv.id = 'typing-indicator';
            typingDiv.innerHTML = `
                <div>
                    <div class="message-bubble bot">
                        <span></span><span></span><span></span>
                    </div>
                </div>
            `;
            this.elements.messages.appendChild(typingDiv);
            this.scrollToBottom();
        }

        removeTypingIndicator() {
            const indicator = document.getElementById('typing-indicator');
            if (indicator) {
                indicator.remove();
            }
        }

        async makeRequest(url, options = {}, retryCount = 0) {
            try {
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), this.options.responseTimeout);

                const response = await fetch(url, {
                    ...options,
                    signal: controller.signal,
                    headers: {
                        'Content-Type': 'application/json',
                        ...options.headers
                    }
                });

                clearTimeout(timeoutId);

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

                return await response.json();
            } catch (error) {
                if (retryCount < this.options.retryAttempts) {
                    await this.delay(this.options.retryDelay);
                    return this.makeRequest(url, options, retryCount + 1);
                }
                throw error;
            }
        }

        async checkAIStatus() {
            try {
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 5000);

                const response = await fetch(`${this.options.apiBase}?action=get_status`, {
                    signal: controller.signal
                });

                clearTimeout(timeoutId);

                if (!response.ok) {
                    throw new Error('API not responding');
                }

                const data = await response.json();
                if (data.success && data.connected) {
                    this.state.isConnected = true;
                    this.updateStatus('Live AI connected');
                } else {
                    this.switchToLocalMode();
                }
            } catch (error) {
                console.warn('Chat API unavailable, using local mode:', error.message);
                this.switchToLocalMode();
            }
        }

        loadSession() {
            const stored = localStorage.getItem(this.options.storageKey);
            if (!stored) return;

            try {
                const session = JSON.parse(stored);
                this.state = { ...this.state, ...session };
            } catch (error) {
                console.warn('Unable to restore chat session:', error.message);
            }
        }

        saveSession() {
            localStorage.setItem(this.options.storageKey, JSON.stringify({
                sessionId: this.state.sessionId,
                useLocalMode: this.state.useLocalMode,
                timestamp: Date.now()
            }));
        }

        saveMessages() {
            sessionStorage.setItem(this.options.messagesKey, JSON.stringify(this.messageHistory));
        }

        restoreMessages() {
            this.elements.messages.innerHTML = '';

            const stored = sessionStorage.getItem(this.options.messagesKey);
            if (!stored) return;

            try {
                this.messageHistory = JSON.parse(stored);
                this.messageHistory.forEach((msg) => {
                    this.renderRestoredMessage(msg.sender, msg.text, msg.time);
                });
            } catch (error) {
                console.warn('Unable to restore chat messages:', error.message);
                this.messageHistory = [];
            }
        }

        renderRestoredMessage(sender, text, isoTime) {
            const messageDate = isoTime ? new Date(isoTime) : new Date();
            const timeStr = messageDate.toLocaleTimeString('en-US', {
                hour: '2-digit',
                minute: '2-digit',
                hour12: true
            });

            const messageDiv = document.createElement('div');
            messageDiv.className = `chat-message ${sender === 'user' ? 'user' : ''}`;
            messageDiv.innerHTML = `
                <div>
                    <div class="message-bubble ${sender === 'user' ? 'user' : 'bot'}">${this.escapeHtml(text)}</div>
                    <div class="chat-timestamp">${timeStr}</div>
                </div>
            `;

            this.elements.messages.appendChild(messageDiv);
            this.scrollToBottom();
        }

        getUserEmail() {
            const sessionEmail = sessionStorage.getItem('user_email');
            if (sessionEmail) return sessionEmail;

            const localEmail = localStorage.getItem('userEmail');
            if (localEmail) return localEmail;

            return `guest_${Math.random().toString(36).slice(2, 11)}@faren.chat`;
        }

        updateStatus(status) {
            if (this.elements.statusSubtitle) {
                this.elements.statusSubtitle.textContent = status;
            }
        }

        updateBadge() {
            if (!this.elements.badge) return;

            if (this.state.unreadCount > 0) {
                this.elements.badge.textContent = this.state.unreadCount;
                this.elements.badge.style.display = 'flex';
            } else {
                this.elements.badge.style.display = 'none';
            }
        }

        setLoading(isLoading) {
            this.state.isLoading = isLoading;

            if (this.elements.sendBtn) {
                this.elements.sendBtn.disabled = isLoading;
                this.elements.sendBtn.style.opacity = isLoading ? '0.6' : '1';
            }

            if (this.elements.input) {
                this.elements.input.disabled = isLoading;
            }
        }

        scrollToBottom() {
            setTimeout(() => {
                if (this.elements.messages) {
                    this.elements.messages.scrollTop = this.elements.messages.scrollHeight;
                }
            }, 60);
        }

        handleOnline() {
            if (!this.state.useLocalMode) {
                this.checkAIStatus();
            }
        }

        handleOffline() {
            this.switchToLocalMode();
        }

        escapeHtml(value) {
            const div = document.createElement('div');
            div.textContent = value;
            return div.innerHTML;
        }

        delay(ms) {
            return new Promise((resolve) => setTimeout(resolve, ms));
        }
    }

    function initializeFarenChat() {
        if (window.__FAREN_LIVE_CHAT_INSTANCE__) {
            return window.__FAREN_LIVE_CHAT_INSTANCE__;
        }

        window.__FAREN_LIVE_CHAT_INSTANCE__ = new FArenLiveChat();
        return window.__FAREN_LIVE_CHAT_INSTANCE__;
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initializeFarenChat, { once: true });
    } else {
        initializeFarenChat();
    }
}
