<div style="display: flex; gap: 20px; height: 85vh; background: #060e1d; border-radius: 12px; border: 1px solid #152c4e; color: #fff; font-family: 'Rajdhani', sans-serif; overflow: hidden; box-sizing: border-box; padding: 10px;">
    
    <div style="width: 30%; border-right: 1px solid rgba(255,255,255,0.05); display: flex; flex-direction: column; gap: 10px; overflow-y: auto; padding-right: 10px;">
        <h3 style="font-family: 'Orbitron'; font-size: 14px; color: #e0a816; border-bottom: 1px solid rgba(255,255,255,0.05); padding-bottom: 10px; margin: 0;">👥 CHAT QUEUE NODES</h3>
        <div id="admin-user-list-target">
            </div>
    </div>

    <div style="width: 70%; display: flex; flex-direction: column; height: 100%;">
        <div style="padding: 10px; background: #0b1528; border-bottom: 1px solid rgba(255,255,255,0.05); font-family: 'Orbitron'; font-size: 13px; color: #ff3366;" id="active-chat-header">
            🔴 NO ACTIVE SESSION SELECT NODE
        </div>
        
        <div id="admin-chat-log-box" style="flex: 1; overflow-y: auto; padding: 15px; display: flex; flex-direction: column; gap: 10px; background: #040a14;">
            <div style="text-align: center; color: gray; margin-top: 50px;">Select a user node from the sidebar queue to stream encryption pathways.</div>
        </div>

        <form id="admin-reply-form" onsubmit="submitAdminReplyNode(event)" style="padding: 10px; background: #0b1528; display: flex; gap: 10px; border-top: 1px solid rgba(255,255,255,0.05);">
            <input type="hidden" id="admin-current-user-id" value="0">
            <input type="text" id="admin-chat-input" placeholder="Type administrative transmission command..." style="flex: 1; background: #060e1d; border: 1px solid #152c4e; color: #fff; padding: 12px; border-radius: 6px; font-size: 13px; outline: none;" disabled>
            <button type="submit" id="admin-send-btn" style="background: #ff3366; color: #fff; border: none; padding: 0 25px; border-radius: 6px; font-family: 'Orbitron'; font-weight: bold; cursor: pointer;" disabled>REPLY</button>
        </form>
    </div>
</div>

<script>
let activeUserInterval = null;
let currentSelectedUserId = 0;

// 🚨 LIVE CHAT SOUND PERSISTENT RING LOOP MATRIX
let globalChatAudioInstance = null;
let activeUnreadTrackerFlag = false;

document.addEventListener("DOMContentLoaded", function() {
    loadAdminChatUsersQueue();
    setInterval(loadAdminChatUsersQueue, 5000); // Auto sync sidebar every 5 seconds
    
    // Core background worker layer loop to execute sound alert boundaries cleanly
    setInterval(managePersistentAudioAlertLoop, 2500);
});

function loadAdminChatUsersQueue() {
    fetch('api/admin_chat_handler.php?action=get_active_chat_users')
        .then(res => res.json())
        .then(users => {
            const listContainer = document.getElementById('admin-user-list-target');
            if(!listContainer) return;
            
            let html = '';
            let unreadDetectedInQueue = false;

            users.forEach(u => {
                let isActive = currentSelectedUserId == u.id ? 'background: #0b1528; border-left: 3px solid #ff3366;' : '';
                
                // Real-time unread dynamic properties classification matching
                let unreadBadgeHtml = '';
                if(parseInt(u.is_unread) === 1) {
                    unreadBadgeHtml = `<span style="background:#ff3366; color:#fff; font-size:10px; padding:2px 6px; border-radius:4px; font-family:'Orbitron'; font-weight:900; float:right; box-shadow: 0 0 8px #ff3366;">NEW</span>`;
                    
                    // Only alert if the unread message is NOT from the currently open chat window
                    if(currentSelectedUserId != u.id) {
                        unreadDetectedInQueue = true;
                    }
                }

                html += `
                <div onclick="selectUserChatNode(${u.id}, '${u.username}')" style="padding: 12px; margin-bottom: 5px; border-radius: 6px; background: rgba(255,255,255,0.02); cursor: pointer; ${isActive}">
                    ${unreadBadgeHtml}
                    <div style="font-weight: bold; color: #fff; font-size: 14px;">@${u.username}</div>
                    <div style="font-size: 12px; color: gray; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; margin-top: 3px;">${u.last_msg || 'Image Attached'}</div>
                </div>`;
            });
            
            listContainer.innerHTML = html || '<div style="color:gray; padding:10px;">No messages queue.</div>';
            
            // Set sync status flags to instruct the audio worker loops pipeline
            activeUnreadTrackerFlag = unreadDetectedInQueue;
        });
}

// 🚨 PERSISTENT BACKGROUND SOUND PLAYER WORKER
function managePersistentAudioAlertLoop() {
    if (activeUnreadTrackerFlag === true) {
        // If an unread ticket exists outside our viewing bounds, play audio loop
        if (!globalChatAudioInstance || globalChatAudioInstance.paused) {
            globalChatAudioInstance = new Audio('../uploads/notification.mp3?v=' + Date.now());
            globalChatAudioInstance.play().catch(err => {
                console.log("Audio needs user interaction gesture layer sync first.");
            });
        }
    } else {
        // If no unread tickets remain, forcibly terminate active noise immediately
        if (globalChatAudioInstance) {
            globalChatAudioInstance.pause();
            globalChatAudioInstance.currentTime = 0;
            globalChatAudioInstance = null;
        }
    }
}

function selectUserChatNode(userId, username) {
    currentSelectedUserId = userId;
    document.getElementById('admin-current-user-id').value = userId;
    document.getElementById('active-chat-header').innerText = `💬 STREAM NODE PROTOCOL: @${username.toUpperCase()}`;
    
    // Enable fields
    document.getElementById('admin-chat-input').removeAttribute('disabled');
    document.getElementById('admin-send-btn').removeAttribute('disabled');
    
    // Clear audio instantly upon interaction pipeline invocation
    if (globalChatAudioInstance) {
        globalChatAudioInstance.pause();
        globalChatAudioInstance.currentTime = 0;
        globalChatAudioInstance = null;
    }
    
    streamActiveUserMessages();
    if(activeUserInterval) clearInterval(activeUserInterval);
    activeUserInterval = setInterval(streamActiveUserMessages, 2000); // Poll stream every 2 seconds
    
    // Instant sidebar synchronization flush to clear status checks on server
    loadAdminChatUsersQueue();
}

function streamActiveUserMessages() {
    if(currentSelectedUserId == 0) return;
    fetch(`api/admin_chat_handler.php?action=get_user_stream_for_admin&user_id=${currentSelectedUserId}`)
        .then(res => res.json())
        .then(data => {
            const logBox = document.getElementById('admin-chat-log-box');
            logBox.innerHTML = '';
            data.forEach(msg => {
                let isAdmin = msg.sender === 'admin';
                let align = isAdmin ? 'align-self: flex-end; background: #ff3366; color: #fff;' : 'align-self: flex-start; background: #152c4e; color: #fff;';
                let media = msg.media_file ? `<br><img src="../uploads/${msg.media_file}" style="max-width:100%; border-radius:6px; margin-top:5px;">` : '';
                
                logBox.innerHTML += `
                    <div style="max-width: 75%; padding: 10px 14px; border-radius: 8px; font-size: 14px; word-break: break-all; ${align}">
                        <div>${msg.message_text}</div>
                        ${media}
                        <div style="font-size: 9px; opacity: 0.6; text-align: right; margin-top:4px;">${msg.created_at}</div>
                    </div>`;
            });
            logBox.scrollTop = logBox.scrollHeight;
        });
}

function submitAdminReplyNode(e) {
    e.preventDefault();
    const input = document.getElementById('admin-chat-input');
    if(!input.value.trim() || currentSelectedUserId == 0) return;

    const formData = new FormData();
    formData.append('action', 'send_admin_reply');
    formData.append('user_id', currentSelectedUserId);
    formData.append('msg', input.value.trim());

    fetch('api/admin_chat_handler.php', { method: 'POST', body: formData })
        .then(res => res.json())
        .then(res => {
            if(res.status === 'success') {
                input.value = '';
                streamActiveUserMessages();
            }
        });
}
</script>