<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="stylesheet" href="<?php echo base_url('public/admin_assets/css/admin-chat.css'); ?>">
</head>

<body>
    <section class="analytics-dashboard">
        <div class="title-wrapper">
            <div class="d-flex justify-content-between align-items-center">
                <h1 class="title">Admin Chat</h1>
                <a href="<?php echo base_url('admin/messages'); ?>" class="btn btn-back">
                    <i class="ri-arrow-left-line"></i> Back
                </a>
            </div>
        </div>

        <div class="chat-container">
            <!-- Events List Column -->
            <div class="chat-events-column" id="eventsColumn">
                <div class="column-header">
                    <h3>Events</h3>
                    <div class="search-box">
                        <i class="ri-search-line"></i>
                        <input type="text" id="eventSearch" placeholder="Search events..." class="search-input">
                    </div>
                </div>
                <div class="events-list" id="eventsList">
                    <div class="loading-state">
                        <i class="ri-loader-4-line spinning"></i>
                        <p>Loading events...</p>
                    </div>
                </div>
            </div>

            <!-- Users List Column -->
            <div class="chat-users-column" id="usersColumn">
                <div class="column-header">
                    <button class="btn-back-mobile" onclick="backToEvents()">
                        <i class="ri-arrow-left-s-line"></i>
                    </button>
                    <h3 id="selectedEventName">Select an event</h3>
                    <!-- With this -->
                    <div class="search-box">
                        <i class="ri-user-3-line"></i>
                        <select id="userDropdown" class="search-input">
                            <option value="">Select a user...</option>
                        </select>
                    </div>
                </div>
                <div class="users-list" id="chatUsersList">
                    <div class="empty-state">
                        <i class="ri-user-3-line"></i>
                        <p>Select an event to view chats</p>
                    </div>
                </div>
            </div>

            <!-- Chat Window Column -->
            <div class="chat-window-column" id="chatWindow">
                <div class="column-header chat-header" id="chatHeader">
                    <button class="btn-back-mobile" onclick="backToUsers()">
                        <i class="ri-arrow-left-s-line"></i>
                    </button>
                    <div class="chat-user-info">
                        <div class="user-avatar">
                            <i class="ri-user-3-fill"></i>
                        </div>
                        <div class="user-details">
                            <h4 id="selectedUserName">Select a user</h4>
                            <span id="selectedUserPhone" class="user-phone"></span>
                        </div>
                    </div>
                </div>
                <div class="chat-messages-area" id="chatMessages">
                    <div class="empty-state">
                        <i class="ri-message-3-line"></i>
                        <p>Select a conversation to start chatting</p>
                    </div>
                </div>
                <div class="chat-input-area" id="chatFooter" style="display: none;">
                    <input type="text" id="chatInput" placeholder="Type your message..." class="chat-input-field">
                    <button class="btn-send" onclick="sendMessage()">
                        <i class="ri-send-plane-fill"></i>
                    </button>
                </div>
            </div>
        </div>
    </section>

    <script src="https://www.gstatic.com/firebasejs/9.22.0/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.22.0/firebase-firestore-compat.js"></script>

    <script>
        let db;
        const userCache = {};
        let allEvents = [];
        let filteredEvents = [];
        let eventUnreadCounts = {};

        // Current state
        let currentEventId = null;
        let currentEventName = null;
        let currentChatId = null;
        let currentUserId = null;
        let messagesUnsubscribe = null;
        let chatsUnsubscribe = null;

        // Initialize Firebase
        async function initFirebase() {
            try {
                const response = await fetch('<?php echo base_url("admin/getFirebaseConfig"); ?>');
                const firebaseConfig = await response.json();
                if (!firebase.apps.length) firebase.initializeApp(firebaseConfig);
                db = firebase.firestore();
                loadEvents();
            } catch (error) {}
        }
        // Call this after Firebase is initialized
        initFirebase().then(() => {
            handleNotificationRedirect();
        });

        async function handleNotificationRedirect() {
            const urlParams = new URLSearchParams(window.location.search);
            const eventId = urlParams.get('eventId');
            const chatId = urlParams.get('chatId');
            const userId = urlParams.get('userId');
            const eventName = urlParams.get('eventName');



            if (eventId && chatId && userId) {

                // ✅ Wait for db to be ready (already initialized by initFirebase)
                let attempts = 0;
                while (!db && attempts < 50) {
                    await new Promise(resolve => setTimeout(resolve, 100));
                    attempts++;
                }

                if (!db) {
                    return;
                }

                // ✅ Wait for events to be loaded (already loading from initFirebase)
                attempts = 0;
                while (allEvents.length === 0 && attempts < 50) {
                    await new Promise(resolve => setTimeout(resolve, 100));
                    attempts++;
                }


                try {
                    // Decode event name from URL or fetch from Firestore
                    let finalEventName = eventName ? decodeURIComponent(eventName) : null;

                    if (!finalEventName) {
                        const eventDoc = await db.collection('events').doc(eventId).get();
                        finalEventName = eventDoc.exists ? eventDoc.data().event_name : 'Event';
                    }


                    // Get user data
                    const userName = await getUserName(userId);
                    const userPhone = await getUserPhone(userId);

                    // Select event
                    selectEvent(eventId, finalEventName);

                    // Wait for chat users to load
                    await new Promise(resolve => setTimeout(resolve, 800));

                    // Select chat
                    selectChat(chatId, userId, userName, userPhone);


                    // Clean URL
                    window.history.replaceState({}, document.title, window.location.pathname);

                } catch (error) {}
            }
        }

        async function getUserName(userId) {
            if (!userId) return 'Unknown User';
            if (userCache[userId]) return userCache[userId];

            try {
                const snap = await db.collection('Users').doc(userId).get();
                if (snap.exists) {
                    const data = snap.data();
                    if (data.userRole === 'user') {
                        const name = data.fullname || 'User';
                        userCache[userId] = name;
                        return name;
                    }
                }
            } catch (err) {}
            return 'User';
        }

        // Get user phone number (kept for chat display but SMS functionality removed)
        async function getUserPhone(userId) {
            if (!userId) return '';
            try {
                const snap = await db.collection('Users').doc(userId).get();
                if (snap.exists) {
                    const data = snap.data();
                    return data.phoneNumber || '';
                }
            } catch (err) {}
            return '';
        }

        // Generate UUID
        function generateUUID() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => (c === 'x' ? Math.random() * 16 | 0 : (Math.random() * 16 | 0 & 0x3 | 0x8)).toString(16));
        }

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

        async function getUnreadCount(eventId, chatId) {
            try {
                const snap = await db
                    .collection('events')
                    .doc(eventId)
                    .collection('admin_chat')
                    .doc(chatId)
                    .collection('Conversations')
                    .where('toID', '==', 'admin')
                    .get();

                let count = 0;

                snap.forEach(doc => {
                    const data = doc.data();
                    if (!data.isRead || data.isRead.admin !== true) {
                        count++;
                    }
                });

                return count;
            } catch (err) {
                return 0;
            }
        }

        // Load all events with admin_chat
        async function loadEvents() {
            const eventsList = document.getElementById('eventsList');
            eventsList.innerHTML =
                '<div class="loading-state"><i class="ri-loader-4-line spinning"></i><p>Loading events...</p></div>';

            try {
                const eventsSnapshot = await db.collection('events').get();
                allEvents = [];
                eventUnreadCounts = {};

                for (const doc of eventsSnapshot.docs) {
                    const data = doc.data();

                    const chatsSnapshot = await db
                        .collection('events')
                        .doc(doc.id)
                        .collection('admin_chat')
                        .get();

                    let lastMessageTimestamp = 0;
                    let totalUnread = 0;

                    // If chats exist → calculate last message + unread
                    if (!chatsSnapshot.empty) {
                        for (const chatDoc of chatsSnapshot.docs) {
                            const chatData = chatDoc.data();

                            if (chatData.lastMessage?.timestamp) {
                                lastMessageTimestamp = Math.max(
                                    lastMessageTimestamp,
                                    chatData.lastMessage.timestamp
                                );
                            }

                            const unreadCount = await getUnreadCount(doc.id, chatDoc.id);
                            totalUnread += unreadCount;
                        }
                    }

                    eventUnreadCounts[doc.id] = totalUnread;

                    // ALWAYS push event
                    allEvents.push({
                        id: doc.id,
                        name: data.event_name || 'Untitled Event',
                        status: data.status || 'draft',
                        start_date: data.start_date || 0,
                        lastMessageTime: lastMessageTimestamp, // 0 if no chats
                        unreadCount: totalUnread // 0 if no chats
                    });
                }

                //Sort:
                //  Events with chats first (recent messages)
                //  Events without chats at bottom
                allEvents.sort((a, b) => {
                    if (a.lastMessageTime === 0 && b.lastMessageTime === 0) return 0;
                    if (a.lastMessageTime === 0) return 1;
                    if (b.lastMessageTime === 0) return -1;
                    return b.lastMessageTime - a.lastMessageTime;
                });

                filteredEvents = [...allEvents];
                displayEvents(filteredEvents);

            } catch (error) {
                eventsList.innerHTML =
                    '<div class="error-state"><i class="ri-error-warning-line"></i><p>Failed to load events</p></div>';
            }
        }

        // Display events list with unread badges
        function displayEvents(events) {
            const eventsList = document.getElementById('eventsList');

            if (events.length === 0) {
                eventsList.innerHTML = '<div class="empty-state"><i class="ri-calendar-line"></i><p>No events with active chats</p></div>';
                return;
            }

            let html = '';
            events.forEach(event => {
                const statusClass = event.status.toLowerCase();
                const dateStr = event.start_date ? new Date(event.start_date).toLocaleDateString('en-US', {
                    month: 'short',
                    day: 'numeric',
                    year: 'numeric'
                }) : 'No date';
                const isSelected = currentEventId === event.id ? 'selected' : '';
                const unreadBadge = event.unreadCount > 0 ? `<span class="event-unread-badge">${event.unreadCount}</span>` : '';

                html += `
                    <div class="event-item ${isSelected}" onclick="selectEvent('${event.id}', '${escapeHtml(event.name)}')">
                        ${unreadBadge}
                        <div class="event-info">
                            <h4>${escapeHtml(event.name)}</h4>
                            <span class="event-date"><i class="ri-calendar-line"></i> ${dateStr}</span>
                        </div>
                    </div>
                `;
            });

            eventsList.innerHTML = html;
        }

        // Select an event and load its chats
        function selectEvent(eventId, eventName) {
            currentEventId = eventId;
            currentEventName = eventName;
            document.getElementById('selectedEventName').textContent = eventName;
            document.getElementById('usersColumn').classList.add('active');

            // Update UI
            displayEvents(filteredEvents);
            loadEventUsers(eventId);

            // Load chats for this event
            loadChatUsers();
        }

        // Load event members into dropdown
        async function loadEventUsers(eventId) {
            const dropdown = document.getElementById('userDropdown');
            dropdown.innerHTML = '<option value="">Select a user...</option>'; // reset

            try {
                const eventDoc = await db.collection('events').doc(eventId).get();
                if (!eventDoc.exists) return;

                const eventData = eventDoc.data();
                const membersMap = eventData.event_members || {};

                for (const userId of Object.keys(membersMap)) {
                    const name = await getUserName(userId);
                    const option = document.createElement('option');
                    option.value = userId;
                    option.textContent = name;
                    dropdown.appendChild(option);
                }
            } catch (err) {}
        }

        // When a user is selected from the dropdown
        document.getElementById('userDropdown').addEventListener('change', async (e) => {
            const userId = e.target.value;
            if (!userId || !currentEventId) return;

            // Reference to chats
            const chatsRef = db.collection('events').doc(currentEventId).collection('admin_chat');
            let chatDoc = null;

            // Check if chat exists
            const snapshot = await chatsRef.where(`participants.${userId}`, '==', true).limit(1).get();

            if (!snapshot.empty) {
                chatDoc = snapshot.docs[0];
            } else {
                // Create new chat
                const newChatId = generateUUID();
                const data = {
                    participants: {
                        admin: true,
                        [userId]: true
                    },
                    lastMessage: {},
                    created_at: Date.now(),
                    updated_at: Date.now()
                };
                await chatsRef.doc(newChatId).set(data);
                chatDoc = await chatsRef.doc(newChatId).get();
            }

            // Open the chat
            const userName = await getUserName(userId);
            const userPhone = await getUserPhone(userId);
            selectChat(chatDoc.id, userId, userName, userPhone);
        });

        // Load chat users with real-time updates
        function loadChatUsers() {
            const usersList = document.getElementById('chatUsersList');
            const chatsRef = db.collection('events').doc(currentEventId).collection('admin_chat');

            if (chatsUnsubscribe) chatsUnsubscribe();

            chatsUnsubscribe = chatsRef.onSnapshot(async (snapshot) => {
                if (snapshot.empty) {
                    usersList.innerHTML = '<div class="empty-state"><i class="ri-message-3-line"></i><p>No conversations yet</p></div>';
                    return;
                }

                const chats = [];
                for (const doc of snapshot.docs) {
                    const data = doc.data();
                    data.chatId = doc.id;

                    // Get unread count for this chat
                    data.unreadCount = await getUnreadCount(currentEventId, doc.id);

                    chats.push(data);
                }

                // Sort by most recent message timestamp
                chats.sort((a, b) => (b.lastMessage?.timestamp || 0) - (a.lastMessage?.timestamp || 0));
                displayChatUsers(chats);
            });
        }

        // Display chat users with unread counts
        async function displayChatUsers(chats) {
            const usersList = document.getElementById('chatUsersList');
            usersList.innerHTML = '';

            for (const chat of chats) {
                const userId = Object.keys(chat.participants || {}).find(id => id !== 'admin');
                if (!userId) continue;

                const lastMsg = chat.lastMessage || {};
                const isUnread = chat.unreadCount > 0;
                const userName = await getUserName(userId);
                const userPhone = await getUserPhone(userId);
                const isSelected = currentChatId === chat.chatId ? 'selected' : '';

                const lastMsgTime = lastMsg.timestamp ?
                    new Date(lastMsg.timestamp).toLocaleTimeString([], {
                        hour: '2-digit',
                        minute: '2-digit'
                    }) : '';

                const unreadBadge = chat.unreadCount > 0 ?
                    `<span class="unread-count">${chat.unreadCount}</span>` : '';

                usersList.innerHTML += `
                    <div class="user-item ${isUnread ? 'unread' : ''} ${isSelected}" 
                         data-chat-id="${chat.chatId}"
                         onclick="selectChat('${chat.chatId}', '${userId}', '${escapeHtml(userName)}', '${escapeHtml(userPhone)}')">
                        <div class="user-avatar">
                            <i class="ri-user-3-fill"></i>
                        </div>
                        <div class="user-info">
                            <div class="user-header">
                                <h4>${escapeHtml(userName)}</h4>
                                ${lastMsgTime ? `<span class="message-time">${lastMsgTime}</span>` : ''}
                            </div>
                            ${userPhone ? `<p class="user-phone">${escapeHtml(userPhone)}</p>` : ''}
                            ${lastMsg.content ? `<p class="last-message">${escapeHtml(lastMsg.content)}</p>` : ''}
                        </div>
                        ${unreadBadge}
                    </div>
                `;
            }
        }

        // Select chat 
        function selectChat(chatId, userId, userName, userPhone) {
            currentChatId = chatId;
            currentUserId = userId;

            document.getElementById('chatWindow').classList.add('active');
            document.getElementById('selectedUserName').textContent = userName || 'Unknown User';
            document.getElementById('selectedUserPhone').textContent = userPhone || '';
            document.getElementById('chatFooter').style.display = 'flex';

            // Update selected state in user list
            document.querySelectorAll('.user-item').forEach(item => {
                item.classList.remove('selected');
            });
            const selectedItem = document.querySelector(`.user-item[data-chat-id="${chatId}"]`);
            if (selectedItem) {
                selectedItem.classList.add('selected');
            }

            loadMessages(chatId);
            markMessagesAsRead(chatId);
        }

        // Load messages with real-time updates
        function loadMessages(chatId) {
            const area = document.getElementById('chatMessages');
            area.innerHTML = '<div class="loading-state"><i class="ri-loader-4-line spinning"></i><p>Loading...</p></div>';

            if (messagesUnsubscribe) messagesUnsubscribe();

            const ref = db.collection('events')
                .doc(currentEventId)
                .collection('admin_chat')
                .doc(chatId)
                .collection('Conversations')
                .orderBy('timestamp', 'asc');

            messagesUnsubscribe = ref.onSnapshot(snap => {
                let html = '';
                snap.forEach(doc => {
                    const msg = doc.data();
                    const isAdmin = msg.fromID === 'admin';
                    const time = new Date(msg.timestamp).toLocaleTimeString([], {
                        hour: '2-digit',
                        minute: '2-digit'
                    });

                    // Add read status for admin messages
                    const readStatus =
                        isAdmin && msg.isRead?.admin === true ?
                        '<i class="ri-check-double-line" style="margin-left:4px;opacity:.7"></i>' :
                        '';


                    html += `
                        <div class="message ${isAdmin ? 'admin' : 'user'}">
                            <div class="message-bubble">
                                <p>${escapeHtml(msg.content)}</p>
                                <span class="message-time">${time}${readStatus}</span>
                            </div>
                        </div>
                    `;
                });
                area.innerHTML = html || '<div class="empty-state"><i class="ri-message-3-line"></i><p>No messages yet.</p></div>';
                area.scrollTop = area.scrollHeight;
            });
        }

        // Send message (chat functionality - kept for chat)
        async function sendMessage() {
            const input = document.getElementById('chatInput');
            const msg = input.value.trim();
            if (!msg || !currentChatId) return;

            const mid = generateUUID();
            const ts = Date.now();

            const data = {
                content: msg,
                fromID: 'admin',
                toID: currentUserId,
                timestamp: ts,
                type: 'text',
                isRead: {
                    admin: true
                },
                messageId: mid
            };

            try {
                // Save message
                await db.collection('events')
                    .doc(currentEventId)
                    .collection('admin_chat')
                    .doc(currentChatId)
                    .collection('Conversations')
                    .doc(mid)
                    .set(data);

                // Update last message
                await db.collection('events')
                    .doc(currentEventId)
                    .collection('admin_chat')
                    .doc(currentChatId)
                    .update({
                        lastMessage: data,
                        updated_at: ts
                    });

                // SEND PUSH NOTIFICATION (Backend)
                fetch('<?php echo base_url("admin/message/sendPush"); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        userId: currentUserId,
                        message: msg,
                        eventName: currentEventName,
                        eventId: currentEventId,
                        conversation_id: currentChatId
                    })
                });

                input.value = '';
            } catch (error) {}
        }

        // Mark messages as read
        async function markMessagesAsRead(chatId) {
            try {
                const snap = await db
                    .collection('events')
                    .doc(currentEventId)
                    .collection('admin_chat')
                    .doc(chatId)
                    .collection('Conversations')
                    .where('toID', '==', 'admin')
                    .get();

                if (snap.empty) return;

                const batch = db.batch();

                snap.forEach(doc => {
                    const data = doc.data();

                    // if admin has NOT read yet
                    if (!data.isRead || data.isRead.admin !== true) {
                        batch.update(doc.ref, {
                            'isRead.admin': true
                        });
                    }
                });

                await batch.commit();
                setTimeout(() => loadEvents(), 300);

            } catch (err) {}
        }

        // Mobile navigation
        function backToEvents() {
            document.getElementById('usersColumn').classList.remove('active');
            document.getElementById('chatWindow').classList.remove('active');
            document.getElementById('chatFooter').style.display = 'none';

            if (chatsUnsubscribe) chatsUnsubscribe();
            if (messagesUnsubscribe) messagesUnsubscribe();

            currentEventId = null;
            currentChatId = null;
        }

        function backToUsers() {
            document.getElementById('chatWindow').classList.remove('active');
            document.getElementById('chatFooter').style.display = 'none';

            if (messagesUnsubscribe) messagesUnsubscribe();

            currentChatId = null;

            // Reload the user list to update selected state
            loadChatUsers();
        }

        // Search functionality
        document.getElementById('eventSearch')?.addEventListener('input', (e) => {
            const query = e.target.value.toLowerCase();
            filteredEvents = allEvents.filter(event =>
                event.name.toLowerCase().includes(query)
            );
            displayEvents(filteredEvents);
        });

        document.getElementById('userSearch')?.addEventListener('input', (e) => {
            const query = e.target.value.toLowerCase();
            const userItems = document.querySelectorAll('.user-item');

            userItems.forEach(item => {
                const text = item.textContent.toLowerCase();
                item.style.display = text.includes(query) ? 'flex' : 'none';
            });
        });

        // Enter key to send message
        document.getElementById('chatInput')?.addEventListener('keypress', e => {
            if (e.key === 'Enter') sendMessage();
        });
    </script>
</body>

</html>