(function() {
    // Configuration
    const API_URL = '../api/messages.php';
    const CHAT_PAGE_URLS = {
        'customer': '../user/messages.php',
        'driver': '../driver/messages.php',
        'admin': '../admin/messages.php'
    };

    let activeBookings = [];
    let userType = '';
    let userId = '';
    let bookingUnreadCounts = {};
    const startTime = Date.now();

    async function init() {
        // Inject button IMMEDIATELY so user sees it even if API is slow
        injectFloatingButton();

        try {
            const response = await fetch(API_URL + '?action=get_active_bookings');
            if (!response.ok) {
                console.log('Floating Chat: API returned error status');
                return;
            }

            const data = await response.json();
            if (data.success) {
                activeBookings = data.bookings;
                userType = data.user_type;
                userId = data.user_id;

                if (activeBookings.length > 0) {
                    setupFirebaseListeners();
                } else {
                    renderChatList(); // Show "No active bookings"
                }
            } else {
                console.log('Floating Chat: API returned success=false');
                // Could be unauthorized - hide button or show login required in list
            }
        } catch (e) {
            console.error('Floating Chat Error:', e);
        }
    }

    function injectFloatingButton() {
        if (document.getElementById('floating-chat-container')) return;

        const btn = document.createElement('div');
        btn.id = 'floating-chat-container';
        // Inline styles to bypass caching and CSS issues
        btn.style.position = 'fixed';
        btn.style.zIndex = '999999';

        const isMobile = window.innerWidth < 1024;
        const isWatch = window.innerWidth < 350;
        const bottomPos = isWatch ? '4rem' : (isMobile ? '6rem' : '2rem');
        const rightPos = isWatch ? '0.75rem' : '1.5rem';
        const btnSize = isWatch ? '3.5rem' : '4.5rem';
        const iconSize = isWatch ? '24px' : '36px';

        btn.innerHTML = `
            <div id="floating-chat-button"
                 style="position: fixed; bottom: ${bottomPos}; right: ${rightPos}; z-index: 1000000;
                        width: ${btnSize}; height: ${btnSize}; background-color: #137fec; color: white;
                        border-radius: 9999px; display: flex; align-items: center; justify-content: center;
                        box-shadow: 0 10px 25px -5px rgba(19, 127, 236, 0.5), 0 8px 10px -6px rgba(19, 127, 236, 0.5);
                        border: 3px solid white; cursor: pointer; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);"
                 onmouseover="this.style.transform='scale(1.1)'"
                 onmouseout="this.style.transform='scale(1)'">
                <span class="material-symbols-outlined" style="font-size: ${iconSize}; font-variation-settings: 'FILL' 1;">chat</span>
                <div id="floating-chat-badge"
                     style="position: absolute; top: -5px; right: -5px; background-color: #ef4444;
                            color: white; font-size: 12px; font-weight: bold; width: 1.5rem; height: 1.5rem;
                            border-radius: 9999px; display: none; align-items: center; justify-content: center;
                            border: 2px solid white; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);">0</div>
            </div>
            <div id="floating-chat-menu"
                 class="hidden"
                 style="position: fixed; bottom: calc(${bottomPos} + 5.5rem); right: 1.5rem; z-index: 1000000;
                        background-color: white; border: 1px solid #e2e8f0; border-radius: 1.25rem;
                        box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); width: 18rem; max-height: 24rem;
                        overflow: hidden; display: none; flex-direction: column; transition: all 0.3s ease;">
                <div style="padding: 1rem; border-bottom: 1px solid #e2e8f0; background-color: rgba(19, 127, 236, 0.05);
                            display: flex; justify-content: space-between; align-items: center;">
                    <h3 style="font-weight: bold; font-size: 0.875rem; color: #1e293b; margin: 0;">Messages</h3>
                    <span style="font-size: 0.625rem; color: #137fec; font-weight: bold; text-transform: uppercase;">Real-time</span>
                </div>
                <div id="floating-chat-list" style="overflow-y: auto; padding: 0.5rem; max-height: 20rem;">
                    <div style="text-align: center; padding: 2rem 1rem; color: #64748b; font-size: 0.75rem;">
                        Loading your conversations...
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(btn);

        const button = document.getElementById('floating-chat-button');
        const menu = document.getElementById('floating-chat-menu');

        button.onclick = () => {
            // Context-aware behavior: if on a booking details page, go directly to chat
            const urlParams = new URLSearchParams(window.location.search);
            const bookingId = urlParams.get('booking_id') || urlParams.get('id');
            const isBookingPage = window.location.pathname.includes('booking_details.php') || window.location.pathname.includes('booking_details.html');

            if (isBookingPage && bookingId && userType) {
                window.location.href = `${CHAT_PAGE_URLS[userType]}?booking_id=${bookingId}`;
                return;
            }

            if (menu.style.display === 'none' || menu.classList.contains('hidden')) {
                menu.style.display = 'flex';
                menu.classList.remove('hidden');
                renderChatList();
            } else {
                menu.style.display = 'none';
                menu.classList.add('hidden');
            }
        };

        document.addEventListener('click', (e) => {
            if (!btn.contains(e.target)) {
                menu.style.display = 'none';
                menu.classList.add('hidden');
            }
        });
    }

    function setupFirebaseListeners() {
        if (typeof firebase === 'undefined') {
            console.error("Firebase not loaded for floating chat");
            return;
        }

        if (firebase.apps.length === 0) {
            // Wait for firebase to be initialized
            document.addEventListener('firebase-ready', () => {
                setupFirebaseListeners();
            }, { once: true });
            return;
        }

        const db = firebase.database();
        const urlParams = new URLSearchParams(window.location.search);
        const currentBookingId = urlParams.get('booking_id') || urlParams.get('id');
        const isChatPage = window.location.pathname.includes('messages.php');

        activeBookings.forEach(booking => {
            const chatRef = db.ref('chats/' + booking.id);
            const storageKey = `last_seen_${userType}_${userId}_${booking.id}`;

            // Initial check
            let lastSeen = parseInt(localStorage.getItem(storageKey) || 0);

            // Listener for real-time notifications
            // Use startTime to filter only messages arriving after the page loaded
            chatRef.orderByChild('timestamp').startAt(startTime + 1).on('child_added', (snapshot) => {
                const msg = snapshot.val();
                if (msg && msg.sender_type !== userType) {
                    // Skip if we're already on this chat page
                    const urlParams = new URLSearchParams(window.location.search);
                    const currentBookingId = urlParams.get('booking_id') || urlParams.get('id');
                    const isChatPage = window.location.pathname.includes('messages.php');

                    if (!(isChatPage && currentBookingId == booking.id)) {
                        showChatHeadNotification(booking, msg);
                    }
                }
            });

            chatRef.on('value', (snapshot) => {
                let unread = 0;
                let maxTimestamp = lastSeen;

                snapshot.forEach(child => {
                    const msg = child.val();
                    if (msg.sender_type !== userType) {
                        if (msg.timestamp > lastSeen) {
                            unread++;
                        }
                    }
                    if (msg.timestamp > maxTimestamp) {
                        maxTimestamp = msg.timestamp;
                    }
                });

                // If we are currently on the chat page for THIS booking, it's not unread
                if (isChatPage && currentBookingId == booking.id) {
                    localStorage.setItem(storageKey, maxTimestamp);
                    unread = 0;
                }

                bookingUnreadCounts[booking.id] = unread;
                updateGlobalBadge();
                renderChatList(); // Update list if menu is open
            });
        });

    }

    function showChatHeadNotification(booking, msg) {
        const container = document.getElementById('floating-chat-container');
        if (!container) return;

        // Remove existing notification if any to show the newest one
        const existing = document.getElementById('chat-notification-bubble');
        if (existing) existing.remove();

        const bubble = document.createElement('div');
        const isWatch = window.innerWidth < 350;
        const bubbleBottom = isWatch ? '8rem' : (window.innerWidth < 1024 ? '11rem' : '7rem');
        const bubbleRight = isWatch ? '0.75rem' : '1.5rem';

        bubble.id = 'chat-notification-bubble';
        bubble.style.cssText = `
            position: fixed;
            bottom: ${bubbleBottom};
            right: ${bubbleRight};
            background: white;
            border-radius: 1rem;
            padding: 0.75rem;
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
            display: flex;
            align-items: center;
            gap: 0.75rem;
            max-width: 16rem;
            cursor: pointer;
            z-index: 999998;
            border: 1px solid #e2e8f0;
            animation: chathead-pop-in 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            transition: all 0.3s ease;
        `;

        const initials = msg.sender_name ? msg.sender_name.charAt(0).toUpperCase() : '?';
        let badgeColor = "#137fec"; // Default
        if (msg.sender_type === 'admin') badgeColor = "#ef4444";
        if (msg.sender_type === 'driver') badgeColor = "#10b981";

        bubble.innerHTML = `
            <div style="width: 2.5rem; height: 2.5rem; border-radius: 9999px; background-color: ${badgeColor}; color: white; display: flex; align-items: center; justify-content: center; font-weight: bold; flex-shrink: 0; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                ${initials}
            </div>
            <div style="flex: 1; min-width: 0;">
                <div class="sender-name" style="font-size: 0.75rem; font-weight: bold; color: #1e293b; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"></div>
                <div class="message-snippet" style="font-size: 0.65rem; color: #64748b; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"></div>
            </div>
            <div onclick="event.stopPropagation(); this.parentElement.remove();" style="color: #cbd5e1; cursor: pointer;">
                <span class="material-symbols-outlined" style="font-size: 16px;">close</span>
            </div>
        `;

        bubble.querySelector('.sender-name').textContent = msg.sender_name || 'Unknown';
        bubble.querySelector('.message-snippet').textContent = msg.message || '';

        bubble.onclick = () => {
            window.location.href = `${CHAT_PAGE_URLS[userType]}?booking_id=${booking.id}`;
        };

        container.appendChild(bubble);

        // Auto-remove after 8 seconds
        setTimeout(() => {
            if (bubble.parentElement) {
                bubble.style.opacity = '0';
                bubble.style.transform = 'translateY(10px) scale(0.95)';
                setTimeout(() => bubble.remove(), 300);
            }
        }, 8000);
    }

    function updateGlobalBadge() {
        const totalUnread = Object.values(bookingUnreadCounts).reduce((a, b) => a + b, 0);
        const badge = document.getElementById('floating-chat-badge');
        if (badge) {
            if (totalUnread > 0) {
                badge.textContent = totalUnread > 99 ? '99+' : totalUnread;
                badge.style.display = 'flex';
            } else {
                badge.style.display = 'none';
            }
        }
    }

    function renderChatList() {
        const list = document.getElementById('floating-chat-list');
        if (!list) return;

        if (activeBookings.length === 0) {
            list.innerHTML = `
                <div style="text-align: center; padding: 2.5rem 1rem; color: #64748b;">
                    <span class="material-symbols-outlined" style="font-size: 32px; color: #cbd5e1; margin-bottom: 0.5rem; display: block;">chat_bubble_outline</span>
                    <p style="font-size: 0.75rem; margin: 0;">No active bookings found.</p>
                </div>
            `;
            return;
        }

        list.innerHTML = activeBookings.map(booking => {
            const unread = bookingUnreadCounts[booking.id] || 0;
            const chatUrl = `${CHAT_PAGE_URLS[userType]}?booking_id=${booking.id}`;
            return `
                <a href="${chatUrl}" style="display: flex; align-items: center; justify-content: space-between; padding: 0.75rem; border-radius: 0.75rem; text-decoration: none; color: inherit; transition: background-color 0.2s;"
                   onmouseover="this.style.backgroundColor='#f1f5f9'" onmouseout="this.style.backgroundColor='transparent'">
                    <div style="display: flex; align-items: center; gap: 0.75rem;">
                        <div style="width: 2.25rem; height: 2.25rem; border-radius: 0.5rem; background-color: rgba(19, 127, 236, 0.1); color: #137fec; display: flex; align-items: center; justify-content: center;">
                            <span class="material-symbols-outlined" style="font-size: 1.25rem;">chat_bubble</span>
                        </div>
                        <div>
                            <p style="font-size: 0.75rem; font-weight: bold; margin: 0;">#${booking.reference_number}</p>
                            <p style="font-size: 0.625rem; color: #64748b; margin: 0;">Click to open chat</p>
                        </div>
                    </div>
                    ${unread > 0 ? `
                    <div style="background-color: #ef4444; color: white; font-size: 0.625rem; font-weight: bold; padding: 0.125rem 0.5rem; border-radius: 9999px;">
                        ${unread}
                    </div>
                    ` : `
                    <span class="material-symbols-outlined" style="color: #cbd5e1; font-size: 1rem;">chevron_right</span>
                    `}
                </a>
            `;
        }).join('');
    }

    // Initialize after a small delay to ensure DOM and other scripts are ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        setTimeout(init, 100);
    }
})();
