/**
 * Chat Helper
 * Handles Firebase Realtime Database integration for booking chats
 * With fallback to local database polling for restricted hosting (InfinityFree, etc.)
 */

window.ChatHelper = {
    init(config) {
        const {
            bookingId,
            userId,
            userName,
            userType,
            chatMessages,
            chatForm,
            messageInput,
            loading,
            appendMessage,
            scrollToBottom,
            onSendNotification,
            useFallback = false,
            apiEndpoint = '../api/chat.php'
        } = config;

        let initialized = false;
        let isSubmissionLocked = false;
        let connectionState = 'connecting';
        let useFallbackMode = useFallback;
        let lastMessageId = 0;
        let pollingInterval = null;

        const loadingEl = document.getElementById('loading') || loading;
        const chatMessagesEl = document.getElementById('chatMessages') || chatMessages;
        const chatFormEl = document.getElementById('chatForm') || chatForm;
        const messageInputEl = document.getElementById('messageInput') || messageInput;

        console.log("[ChatHelper] Initializing for booking:", bookingId, "User:", userId, "Type:", userType);

        // Form submission handler
        if (chatFormEl) {
            console.log("[ChatHelper] Attaching form handler");
            chatFormEl.onsubmit = null;

            chatFormEl.addEventListener('submit', function(e) {
                e.preventDefault();
                e.stopPropagation();

                if (isSubmissionLocked) return false;

                const message = messageInputEl ? messageInputEl.value.trim() : '';
                if (!message) return false;

                if (!initialized && !useFallbackMode) {
                    alert("Chat is still connecting. Please wait a moment.");
                    return false;
                }

                if (useFallbackMode) {
                    sendMessageFallback(message);
                } else {
                    sendMessageFirebase(message);
                }
                return false;
            });
            
            if (messageInputEl) {
                messageInputEl.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter' && !e.shiftKey) {
                        e.preventDefault();
                        chatFormEl.dispatchEvent(new Event('submit', { cancelable: true }));
                    }
                });
            }
        }

        function sendMessageFirebase(message) {
            try {
                const database = firebase.database();
                const chatRef = database.ref('chats/' + bookingId);
                
                isSubmissionLocked = true;
                const newMessage = {
                    sender_id: userId,
                    sender_name: userName,
                    sender_type: userType,
                    message: message,
                    timestamp: firebase.database.ServerValue.TIMESTAMP
                };

                if (typeof appendMessage === 'function') {
                    appendMessage({ ...newMessage, timestamp: Date.now() });
                    if (typeof scrollToBottom === 'function') scrollToBottom();
                }

                chatRef.push(newMessage).then(() => {
                    if (messageInputEl) messageInputEl.value = '';
                    isSubmissionLocked = false;
                    if (typeof onSendNotification === 'function') onSendNotification(message);
                }).catch(err => {
                    isSubmissionLocked = false;
                    console.error("[ChatHelper] Firebase Send Error:", err);
                    
                    // If Firebase fails, try fallback
                    if (err.code === 'PERMISSION_DENIED' || err.message?.includes('network')) {
                        console.log("[ChatHelper] Switching to fallback mode");
                        enableFallbackMode();
                        sendMessageFallback(message);
                    } else {
                        alert("Failed to send: " + (err.message || 'Unknown error'));
                    }
                });
            } catch (err) {
                isSubmissionLocked = false;
                console.error("[ChatHelper] Error:", err);
                enableFallbackMode();
                sendMessageFallback(message);
            }
        }

        async function sendMessageFallback(message) {
            isSubmissionLocked = true;
            
            // We removed the optimistic append to prevent duplication with the polling mechanism.
            // Messages will appear once confirmed by the server and fetched via poll.

            try {
                const response = await fetch(apiEndpoint, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        booking_id: bookingId,
                        user_id: userId,
                        sender_type: userType, // Added this line
                        message: message
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    if (messageInputEl) messageInputEl.value = '';
                    if (typeof onSendNotification === 'function') onSendNotification(message);

                    // Delay slightly to give the DB time to commit, then poll
                    setTimeout(() => pollMessages(), 500);
                } else {
                    alert("Failed to send: " + (data.error || 'Unknown error'));
                }
            } catch (err) {
                console.error("[ChatHelper] Fallback send error:", err);
                alert("Failed to send message. Please try again.");
            } finally {
                isSubmissionLocked = false;
            }
        }

        function enableFallbackMode() {
            if (useFallbackMode) return;
            useFallbackMode = true;
            console.log("[ChatHelper] Fallback mode enabled");
            
            // Show fallback mode indicator
            const indicator = document.createElement('div');
            indicator.id = 'fallback-indicator';
            indicator.className = 'bg-amber-100 border border-amber-300 text-amber-800 px-3 py-1 text-xs text-center';
            indicator.innerHTML = '⚠ Using fallback mode (real-time updates limited). <a href="#" onclick="location.reload()" class="underline">Retry connection</a>';
            
            const header = document.querySelector('header');
            if (header && !document.getElementById('fallback-indicator')) {
                header.insertAdjacentElement('afterend', indicator);
            }
            
            // Start polling
            startPolling();
        }

        async function pollMessages() {
            try {
                const response = await fetch(`${apiEndpoint}?action=get_messages&booking_id=${bookingId}&user_id=${userId}&last_id=${lastMessageId}&sender_type=${userType}`);
                const data = await response.json();
                
                if (data.success && data.messages) {
                    data.messages.forEach(msg => {
                        const msgId = parseInt(msg.id);
                        if (msgId > lastMessageId) {
                            lastMessageId = msgId;
                            if (typeof appendMessage === 'function') {
                                appendMessage({
                                    id: msg.id,
                                    sender_id: msg.sender_id,
                                    sender_name: msg.sender_name || (msg.first_name + ' ' + (msg.last_name || '')),
                                    sender_type: msg.sender_type || msg.user_type,
                                    message: msg.message,
                                    timestamp: new Date(msg.created_at).getTime()
                                });
                            }
                        }
                    });
                    if (data.messages.length > 0 && typeof scrollToBottom === 'function') scrollToBottom();
                }
            } catch (err) {
                console.error("[ChatHelper] Polling error:", err);
            }
        }

        function startPolling() {
            if (pollingInterval) return;
            console.log("[ChatHelper] Starting message polling");
            pollMessages(); // Initial poll
            pollingInterval = setInterval(pollMessages, 3000); // Poll every 3 seconds
        }

        function stopPolling() {
            if (pollingInterval) {
                clearInterval(pollingInterval);
                pollingInterval = null;
            }
        }

        function showError(title, message, code = '') {
            connectionState = 'error';
            if (loadingEl) {
                const codeDisplay = code ? `<p class="text-[10px] text-rose-400 mt-1">Code: ${code}</p>` : '';
                loadingEl.innerHTML = `
                    <div class="text-center p-6 bg-rose-50 dark:bg-rose-900/20 border border-rose-200 dark:border-rose-800 rounded-xl max-w-md mx-auto">
                        <span class="material-symbols-outlined text-rose-500 text-3xl mb-2">error</span>
                        <p class="text-sm font-bold text-rose-700">${title}</p>
                        <p class="text-xs text-rose-600 mt-1">${message}</p>
                        ${codeDisplay}
                        <div class="mt-4 flex gap-2 justify-center">
                            <button onclick="window.location.reload()" class="px-4 py-2 bg-rose-500 text-white text-xs font-bold rounded-lg">Retry</button>
                            <button onclick="document.getElementById('use-fallback-btn').click()" class="px-4 py-2 bg-amber-500 text-white text-xs font-bold rounded-lg">Use Fallback</button>
                        </div>
                        <button id="use-fallback-btn" style="display:none" onclick="window.ChatHelper.enableFallbackMode && window.ChatHelper.enableFallbackMode()"></button>
                    </div>
                `;
            }
        }

        function showConnecting() {
            if (loadingEl) {
                loadingEl.innerHTML = `
                    <div class="flex flex-col items-center justify-center py-10">
                        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mb-3"></div>
                        <p class="text-xs text-gray-500">Connecting to chat server...</p>
                        <p class="text-[10px] text-gray-400 mt-2">This may take a few seconds</p>
                    </div>
                `;
            }
        }

        function showInfinityFreeWarning() {
            if (loadingEl) {
                loadingEl.innerHTML = `
                    <div class="text-center p-6 bg-amber-50 border border-amber-200 rounded-xl max-w-md mx-auto">
                        <span class="material-symbols-outlined text-amber-500 text-3xl mb-2">cloud_off</span>
                        <p class="text-sm font-bold text-amber-800">Hosting Restriction Detected</p>
                        <p class="text-xs text-amber-700 mt-2">
                            Your hosting provider (InfinityFree) blocks Firebase connections.<br>
                            Switching to fallback mode with polling.
                        </p>
                        <button onclick="window.location.reload()" class="mt-3 px-4 py-2 bg-amber-500 text-white text-xs font-bold rounded-lg">
                            Continue with Fallback
                        </button>
                    </div>
                `;
            }
        }

        async function startChat(firebaseDetail = {}) {
            if (initialized) return;

            // Check if this is InfinityFree hosting
            const isInfinityFree = window.location.hostname.includes('infinityfree') || 
                                   window.location.hostname.includes('free.nf');

            if (firebaseDetail.success === false) {
                console.error("[ChatHelper] Firebase config error:", firebaseDetail);
                
                // If on InfinityFree, auto-enable fallback
                if (isInfinityFree) {
                    console.log("[ChatHelper] InfinityFree detected with config error, using fallback");
                    showInfinityFreeWarning();
                    setTimeout(() => enableFallbackMode(), 2000);
                    return;
                }

                let errorTitle = "Configuration Error";
                let errorMessage = firebaseDetail.error || "Unknown error";
                let errorCode = firebaseDetail.code || '';

                switch (firebaseDetail.code) {
                    case 'CONFIG_INVALID':
                        errorTitle = "Invalid Configuration";
                        errorMessage = `Missing fields: ${(firebaseDetail.errors || []).join(', ')}`;
                        break;
                    case 'SDK_MISSING':
                        errorTitle = "SDK Not Loaded";
                        errorMessage = "Firebase SDK could not be loaded";
                        break;
                    case 'TIMEOUT':
                        errorTitle = "Connection Timed Out";
                        errorMessage = "Could not fetch configuration";
                        break;
                }

                showError(errorTitle, errorMessage, errorCode);
                return;
            }

            // Check Firebase availability
            if (typeof firebase === 'undefined' || !firebase.apps || firebase.apps.length === 0) {
                if (isInfinityFree) {
                    showInfinityFreeWarning();
                    setTimeout(() => enableFallbackMode(), 2000);
                } else {
                    showError("Not Initialized", "Firebase SDK not available", 'NOT_INITIALIZED');
                }
                return;
            }

            try {
                const appOptions = firebase.app().options;
                const dbUrl = appOptions.databaseURL;

                if (!dbUrl || dbUrl.includes('example.com')) {
                    showError("Invalid URL", "Database URL is a placeholder", 'INVALID_DB_URL');
                    return;
                }

                const database = firebase.database();
                const chatRef = database.ref('chats/' + bookingId);

                // Connection timeout
                let initializedData = false;
                const connectionTimeout = setTimeout(() => {
                    if (!initializedData) {
                        console.warn("[ChatHelper] Connection timeout");
                        if (isInfinityFree) {
                            showInfinityFreeWarning();
                            setTimeout(() => enableFallbackMode(), 2000);
                        }
                    }
                }, 8000);

                // Test connection
                chatRef.once('value')
                    .then((snapshot) => {
                        initializedData = true;
                        clearTimeout(connectionTimeout);
                        initialized = true;
                        connectionState = 'connected';

                        if (loadingEl) loadingEl.remove();

                        if (!snapshot.exists() && chatMessagesEl && !document.getElementById('no-messages')) {
                            chatMessagesEl.innerHTML += `
                                <div id="no-messages" class="flex flex-col items-center justify-center py-10 text-gray-500">
                                    <span class="material-symbols-outlined text-4xl mb-2">chat_bubble_outline</span>
                                    <p class="text-xs">No messages yet. Start the conversation!</p>
                                </div>
                            `;
                        }
                    })
                    .catch((err) => {
                        initializedData = true;
                        clearTimeout(connectionTimeout);
                        console.error("[ChatHelper] Firebase error:", err);

                        // Check if InfinityFree or permission/network error
                        if (isInfinityFree || 
                            err.code === 'PERMISSION_DENIED' || 
                            err.message?.includes('network') ||
                            err.message?.includes('blocked')) {
                            showInfinityFreeWarning();
                            setTimeout(() => enableFallbackMode(), 2000);
                        } else {
                            showError("Connection Error", err.message, err.code);
                        }
                    });

                // Listen for new messages
                chatRef.on('child_added', (snapshot) => {
                    const noMsg = document.getElementById('no-messages');
                    if (noMsg) noMsg.remove();
                    if (loadingEl && loadingEl.parentElement) loadingEl.remove();

                    const msg = snapshot.val();
                    if (msg && typeof appendMessage === 'function') {
                        appendMessage(msg);
                        if (typeof scrollToBottom === 'function') scrollToBottom();
                    }
                });

            } catch (err) {
                console.error("[ChatHelper] Fatal error:", err);
                if (isInfinityFree) {
                    showInfinityFreeWarning();
                    setTimeout(() => enableFallbackMode(), 2000);
                } else {
                    showError("Error", err.message, 'INIT_FATAL');
                }
            }
        }

        // Initialize
        if (useFallbackMode) {
            console.log("[ChatHelper] Initializing in Fallback Mode immediately");
            initialized = true;
            if (loadingEl) loadingEl.remove();
            startPolling();
        } else if (typeof firebase !== 'undefined' && firebase.apps && firebase.apps.length > 0) {
            console.log("[ChatHelper] Firebase already initialized, starting immediately");
            startChat();
        } else {
            showConnecting();
            
            // Store handler reference so we can check if it was called
            let eventReceived = false;
            
            const firebaseReadyHandler = (e) => {
                eventReceived = true;
                document.removeEventListener('firebase-ready', firebaseReadyHandler);
                console.log("[ChatHelper] Firebase ready event received");
                startChat(e.detail);
            };
            document.addEventListener('firebase-ready', firebaseReadyHandler);
            
            console.log("[ChatHelper] Waiting for firebase-ready event...");

            // Timeout - if event never comes, show error or fallback
            setTimeout(() => {
                if (!initialized && !eventReceived) {
                    console.error("[ChatHelper] Timeout waiting for firebase-ready event");
                    const isInfinityFree = window.location.hostname.includes('infinityfree') || 
                                           window.location.hostname.includes('free.nf');
                    if (isInfinityFree) {
                        showInfinityFreeWarning();
                        setTimeout(() => enableFallbackMode(), 2000);
                    } else if (typeof firebase === 'undefined') {
                        showError("SDK Not Loaded", "Firebase SDK could not load. Check console for errors.", 'SDK_NOT_LOADED');
                    } else {
                        showError("Timeout", "Firebase initialization timed out. Check console.", 'TIMEOUT');
                    }
                }
            }, 12000);
        }

        // Expose fallback enable function
        this.enableFallbackMode = enableFallbackMode;
    }
};
