(function ($) {
    let firebaseApp, auth, db, storage, user = null;
    let chatOpen = false;
    let users = [];
    let selectedUser = null;
    let messages = [];

    // Firebase config from PHP
    const firebaseConfig = window.appLocalizer || {};

    // Load Firebase if available
    function initFirebase() {
        if (window.firebase && firebaseConfig && firebaseConfig.apiKey) {
            firebaseApp = firebase.initializeApp(firebaseConfig);
            auth = firebase.auth();
            db = firebase.firestore();
            storage = firebase.storage();
        }
    }

    // Update user status
    function updateUserStatus(user, isOnline) {
        if (!db) return;
        
        db.collection('users').doc(user.uid).set({
            uid: user.uid,
            displayName: user.displayName || user.email,
            email: user.email,
            photoURL: user.photoURL || '',
            isOnline: isOnline,
            lastSeen: firebase.firestore.FieldValue.serverTimestamp()
        }, { merge: true });
    }

    // Get chat ID for two users
    function getChatId(uid1, uid2) {
        return [uid1, uid2].sort().join('_');
    }

    // Render users list
    function renderUsers() {
        const $usersList = $('#acb_users_list');
        $usersList.empty();
        
        // console.log('Rendering users:', users);
        
        if (users.length === 0) {
            $usersList.append(`
                <div class="acb-no-users">
                    <p>No other users online</p>
                </div>
            `);
            return;
        }
        
        users.forEach(userItem => {
            if (userItem.uid !== user.uid) {
                $usersList.append(`
                    <div class="acb-user-item" data-uid="${userItem.uid}">
                        <div class="acb-user-avatar-container">
                            <img src="${userItem.photoURL || 'https://via.placeholder.com/40'}" class="acb-user-avatar" />
                            <span class="acb-online-indicator ${userItem.isOnline ? 'online' : 'offline'}"></span>
                        </div>
                        <div class="acb-user-details">
                            <h5>${userItem.displayName || userItem.email}</h5>
                            <span class="acb-user-status">${userItem.isOnline ? 'Online' : 'Offline'}</span>
                        </div>
                    </div>
                `);
            }
        });
    }

    // Render messages
    function renderMessages() {
        const $logs = $('#acb_chat_logs');
        $logs.empty();
        
        messages.forEach(msg => {
            const isOwn = user && msg.uid === user.uid;
            let messageContent = '';
            
            if (msg.type === 'image') {
                messageContent = `<img src="${msg.fileUrl}" alt="Shared image" class="acb-message-image" />`;
            } else if (msg.type === 'file') {
                messageContent = `
                    <div class="acb-message-file">
                        <i class="fas fa-file"></i>
                        <a href="${msg.fileUrl}" target="_blank">${msg.fileName}</a>
                    </div>
                `;
            } else {
                messageContent = `<p>${msg.text}</p>`;
            }
            
            $logs.append(`
                <div class="acb-message ${isOwn ? 'own' : 'other'}">
                    <img src="${msg.photoURL || 'https://via.placeholder.com/32'}" class="acb-message-avatar" />
                    <div class="acb-message-content">
                        <div class="acb-message-header">
                            <span class="acb-message-sender">${msg.displayName}</span>
                            <span class="acb-message-time">${formatTime(msg.timestamp)}</span>
                        </div>
                        <div class="acb-message-body">
                            ${messageContent}
                        </div>
                    </div>
                </div>
            `);
        });
        $logs.scrollTop($logs[0].scrollHeight);
    }

    // Listen for users
    function listenForUsers() {
        if (!db) return;
        
        // console.log('Setting up users listener...');
        
        const usersQuery = db.collection('users').where('uid', '!=', user.uid);
        usersQuery.onSnapshot(snapshot => {
            users = [];
            snapshot.forEach(doc => {
                users.push({ id: doc.id, ...doc.data() });
            });
            // console.log('Users updated:', users);
            renderUsers();
        }, error => {
            console.error('Error listening for users:', error);
        });
    }

    // Listen for messages when a user is selected
    function listenForMessages() {
        if (!db || !selectedUser) return;
        
        // console.log('Setting up messages listener for user:', selectedUser.uid);
        
        const chatId = getChatId(user.uid, selectedUser.uid);
        const messagesQuery = db.collection('chats').doc(chatId).collection('messages').orderBy('timestamp', 'asc');
        
        messagesQuery.onSnapshot(snapshot => {
            messages = [];
            snapshot.forEach(doc => {
                messages.push({ id: doc.id, ...doc.data() });
            });
            // console.log('Messages updated:', messages);
            renderMessages();
        }, error => {
            console.error('Error listening for messages:', error);
        });
    }

    // Send message
    function sendMessage(text, type = 'text', fileUrl = null, fileName = null) {
        if (!user || !selectedUser || !db || (!text.trim() && !fileUrl)) return;
        
        const chatId = getChatId(user.uid, selectedUser.uid);
        const messageData = {
            text: text,
            uid: user.uid,
            displayName: user.displayName || user.email,
            email: user.email,
            photoURL: user.photoURL || '',
            timestamp: firebase.firestore.FieldValue.serverTimestamp(),
            type: type
        };

        if (fileUrl) {
            messageData.fileUrl = fileUrl;
            messageData.fileName = fileName;
        }

        db.collection('chats').doc(chatId).collection('messages').add(messageData);
        
        if (type === 'text') {
            $('#msg').val('');
        }
    }

    // Handle file upload
    function handleFileUpload(file) {
        if (!storage || !file) return;
        
        const storageRef = storage.ref(`chat-files/${Date.now()}_${file.name}`);
        storageRef.put(file).then(snapshot => {
            return snapshot.ref.getDownloadURL();
        }).then(downloadURL => {
            const fileType = file.type.startsWith('image/') ? 'image' : 'file';
            sendMessage('', fileType, downloadURL, file.name);
        }).catch(error => {
            console.error('Error uploading file:', error);
        });
    }

    // Format time
    function formatTime(timestamp) {
        if (!timestamp) return '';
        const date = timestamp.toDate ? timestamp.toDate() : new Date(timestamp);
        return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    }

    // Show/hide chat
    function toggleChat(open) {
        chatOpen = open !== undefined ? open : !chatOpen;
        if (chatOpen) {
            $('.chat-box').show();
        } else {
            $('.chat-box').hide();
        }
    }

    // Show auth UI
    function showAuthUI() {
        $('#acb_auth_area').show();
        $('#acb_chat_form').hide();
        $('#acb_users_list').hide();
        $('#acb_auth_area').html(`
            <div class="acb-auth-box">
                <button id="acb_google_signin" class="acb-google-btn"><i class="fa fa-google"></i> Sign in with Google</button>
                <div class="acb-divider"><span>or</span></div>
                <input type="email" id="acb_email" placeholder="Email" />
                <input type="password" id="acb_password" placeholder="Password" />
                <button id="acb_email_signin" class="acb-email-btn">Sign in with Email</button>
            </div>
        `);
    }

    // Hide auth UI and show chat
    function hideAuthUI() {
        $('#acb_auth_area').hide();
        $('#acb_chat_form').hide();
        $('#acb_users_list').show();
        $('.chat-box-body').hide();
        $('.chat-input').hide();
        listenForUsers();
    }

    // Auth logic
    function setupAuth() {
        if (!auth) return;
        
        auth.onAuthStateChanged(function (firebaseUser) {
            user = firebaseUser;
            if (user) {
                updateUserStatus(user, true);
                hideAuthUI();
            } else {
                showAuthUI();
                users = [];
                messages = [];
                selectedUser = null;
                renderUsers();
                renderMessages();
            }
        });

        // Google sign-in
        $(document).on('click', '#acb_google_signin', function (e) {
            e.preventDefault();
            const provider = new firebase.auth.GoogleAuthProvider();
            auth.signInWithPopup(provider).catch(console.error);
        });

        // Email sign-in
        $(document).on('click', '#acb_email_signin', function (e) {
            e.preventDefault();
            const email = $('#acb_email').val();
            const password = $('#acb_password').val();
            auth.signInWithEmailAndPassword(email, password).catch(console.error);
        });
    }

    // UI events
    $(document).ready(function () {
        // Init Firebase
        initFirebase();
        setupAuth();

        // Chat open/close
        $('#chat-circle').on('click', function () {
            toggleChat(true);
        });
        $('.chat-box-toggle').on('click', function () {
            toggleChat(false);
        });

        // User selection
        $(document).on('click', '.acb-user-item', function () {
            const uid = $(this).data('uid');
            // console.log('User clicked:', uid);
            
            selectedUser = users.find(u => u.uid === uid);
            // console.log('Selected user:', selectedUser);
            
            if (!selectedUser) {
                console.error('User not found:', uid);
                return;
            }
            
            // Update UI
            $('.acb-user-item').removeClass('active');
            $(this).addClass('active');
            
            // Update chat header
            $('.chat-box-header span:first').text(selectedUser.displayName || selectedUser.email);
            
            // Show chat area and hide users list
            $('.chat-box-body').show();
            $('.chat-input').show();
            $('#acb_users_list').hide();
            
            // Listen for messages
            listenForMessages();
        });

        // Add button to show users list
        $('.chat-box-header').append('<button id="acb_show_users" class="acb-show-users-btn"><i class="fa fa-users"></i></button>');
        
        // Show users list button
        $(document).on('click', '#acb_show_users', function () {
            $('#acb_users_list').show();
            $('.chat-box-body').hide();
            $('.chat-input').hide();
            selectedUser = null;
            messages = [];
        });

        // Send message
        $('#acb_chat_form').on('submit', function (e) {
            e.preventDefault();
            const text = $('#msg').val();
            sendMessage(text);
        });

        // File upload
        $('#acb_file_input').on('change', function (e) {
            const file = e.target.files[0];
            if (file) {
                handleFileUpload(file);
            }
            $(this).val('');
        });

        // File upload trigger
        $('#acb_attach_btn').on('click', function (e) {
            e.preventDefault();
            $('#acb_file_input').click();
        });

        // Hide chat by default
        toggleChat(false);
    });

})(jQuery); 