<style>
    /* --- FONDO OSCURO (BACKDROP) --- */
    #custom-backdrop {
        display: none; position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
        background: rgba(0,0,0,0.1); z-index: 9990;
    }

    /* --- PANEL LATERAL --- */
    #sidebar-wrapper {
        position: fixed; top: 0; right: -320px; width: 300px; height: 100vh;
        background: #fff; z-index: 9995; transition: right 0.3s ease;
        box-shadow: -5px 0 15px rgba(0,0,0,0.1); display: block !important;
    }

    /* --- PANEL VENTANA --- */
    #window-wrapper {
        position: fixed; top: 0; right: -400px; width: 350px; height: 100vh;
        background: #fff; z-index: 9999; transition: right 0.3s ease;
        box-shadow: -5px 0 15px rgba(0,0,0,0.2); display: block !important;
    }

    .force-open { right: 0 !important; }

    .user-box { height: 100%; display: flex; flex-direction: column; }
    .main-friend-list { flex: 1; overflow-y: auto; height: auto !important; }
    .main-friend-chat { 
        flex: 1; overflow-y: auto; height: calc(100% - 130px) !important; padding-bottom: 20px; 
    }
</style>

<li class="header-notification">
    <div class="dropdown-primary dropdown">
        <div class="displayChatbox" id="chat-trigger-original" style="cursor: pointer;">
            <i class="feather icon-message-square"></i>
            <span class="badge bg-c-green" id="chat-badge" style="display:none">0</span>
        </div>
    </div>
</li>

<div id="chat-plugin-container">
    <div id="custom-backdrop"></div>

    <div id="sidebar-wrapper" class="users p-chat-user">
        <div class="had-container" style="height:100%">
            <div class="p-fixed users-main" style="position: relative; height:100%; width:100%;">
                <div class="user-box">
                    <div class="chat-search-box">
                        <a class="back_friendlist" id="btn-close-sidebar"> <i class="feather icon-x"></i> </a>
                        <div class="right-icon-control">
                            <div class="input-group input-group-button">
                                <input type="text" id="inp-search" class="form-control" placeholder="Buscar...">
                                <div class="input-group-append">
                                    <button class="btn btn-primary waves-effect waves-light" id="btn-new-chat">
                                        <i class="feather icon-plus"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="main-friend-list" id="list-area"></div>
                </div>
            </div>
        </div>
    </div>

    <div id="window-wrapper" class="showChat_inner">
        <div class="media chat-inner-header">
            <a class="back_chatBox" id="btn-back-list">
                <i class="feather icon-chevron-left"></i> <span id="txt-chat-title">Usuario</span>
            </a>
        </div>
        <div class="main-friend-chat" id="msg-area"></div>
        <div class="chat-reply-box">
            <div class="right-icon-control">
                <div class="input-group input-group-button">
                    <input type="text" class="form-control" id="inp-msg" placeholder="Escribe..." autocomplete="off">
                    <div class="input-group-append">
                        <button class="btn btn-primary waves-effect waves-light" id="btn-send">
                            <i class="feather icon-message-circle"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
console.log("Cargando Chat System (Modo Seguro - Sync Imágenes)...");

const ChatSystem = (function() {
    const CONFIG = {
        IDU: <?php echo isset($_SESSION['IDU']) ? (int)$_SESSION['IDU'] : 0; ?>,
        DB: 'MS_Usuario',
        URL_AJAX: '../librerias/AJAX/',
        // Imagen por defecto oficial del sistema
        DEF_IMG: 'http://167.172.224.160/MS/librerias/Archivos/usuario.png'
    };

    let activeChatID = 0;
    let poller = null;
    let UI = {};

    function init() {
        if (CONFIG.IDU === 0) return;

        let oldTrigger = document.getElementById('chat-trigger-original');
        if(oldTrigger) {
            let newTrigger = oldTrigger.cloneNode(true);
            oldTrigger.parentNode.replaceChild(newTrigger, oldTrigger);
            newTrigger.id = 'chat-trigger-clean';
            newTrigger.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                openSidebar();
            });
        }

        UI = {
            backdrop: document.getElementById('custom-backdrop'),
            sidebar: document.getElementById('sidebar-wrapper'),
            window: document.getElementById('window-wrapper'),
            listArea: document.getElementById('list-area'),
            msgArea: document.getElementById('msg-area'),
            input: document.getElementById('inp-msg'),
            title: document.getElementById('txt-chat-title'),
            search: document.getElementById('inp-search'),
            closeSidebar: document.getElementById('btn-close-sidebar'),
            newChatBtn: document.getElementById('btn-new-chat'),
            backBtn: document.getElementById('btn-back-list'),
            sendBtn: document.getElementById('btn-send')
        };

        UI.backdrop.onclick = closeAll;
        UI.closeSidebar.onclick = closeAll;
        UI.backBtn.onclick = closeWindowOnly;
        UI.newChatBtn.onclick = loadDirectory;
        UI.search.onkeyup = (e) => doSearch(e.target.value);
        UI.sendBtn.onclick = sendMessage;
        UI.input.onkeypress = (e) => { if(e.key === 'Enter') sendMessage(); };
    }

    function openSidebar() {
        UI.backdrop.style.display = 'block';
        UI.sidebar.classList.add('force-open');
        loadRecents();
    }

    function closeAll() {
        UI.sidebar.classList.remove('force-open');
        UI.window.classList.remove('force-open');
        UI.backdrop.style.display = 'none';
        activeChatID = 0;
        stopPolling();
    }

    function openChat(id, name) {
        activeChatID = id;
        UI.title.innerText = name;
        UI.window.classList.add('force-open');
        UI.msgArea.innerHTML = '<div class="text-center p-4 text-muted">Cargando...</div>';
        loadMessages();
        startPolling();
    }

    function closeWindowOnly() {
        UI.window.classList.remove('force-open');
        activeChatID = 0;
        stopPolling();
        loadRecents();
    }

    // --- DATA (AJAX) - MODIFICADO: Agregada columna Foto_Thumb ---

    async function loadRecents() {
        const sql = `
            SELECT U.IDU, U.Nombre, U.Foto_Thumb, MAX(M.TimeStamp) as UltimoMsg
            FROM Usuarios U
            JOIN Chat_Mensajes M ON (
                (M.ID_Remitente = ${CONFIG.IDU} AND M.ID_Destinatario = U.IDU) 
                OR 
                (M.ID_Destinatario = ${CONFIG.IDU} AND M.ID_Remitente = U.IDU)
            )
            WHERE U.IDU != ${CONFIG.IDU}
            GROUP BY U.IDU, U.Nombre, U.Foto_Thumb
            ORDER BY UltimoMsg DESC LIMIT 20
        `;
        const res = await api(sql, 'SELECT');
        renderList(res.data);
    }

    async function loadDirectory() {
        UI.listArea.innerHTML = '<div class="text-center p-2 text-muted">Cargando...</div>';
        const sql = `SELECT IDU, Nombre, Foto_Thumb FROM Usuarios WHERE IDU != ${CONFIG.IDU} ORDER BY Nombre ASC LIMIT 50`;
        const res = await api(sql, 'SELECT');
        renderList(res.data);
    }

    let searchT;
    function doSearch(txt) {
        clearTimeout(searchT);
        if(!txt) { loadRecents(); return; }
        searchT = setTimeout(async () => {
            const sql = `SELECT IDU, Nombre, Foto_Thumb FROM Usuarios WHERE Nombre LIKE '%${txt}%' AND IDU != ${CONFIG.IDU} LIMIT 10`;
            const res = await api(sql, 'SELECT');
            renderList(res.data);
        }, 300);
    }

    async function loadMessages() {
        if(activeChatID === 0) return;
        // Agregamos un LEFT JOIN para obtener la foto del remitente del mensaje
        const sql = `SELECT M.*, U.Foto_Thumb 
                     FROM Chat_Mensajes M
                     LEFT JOIN Usuarios U ON M.ID_Remitente = U.IDU
                     WHERE (M.ID_Remitente = ${CONFIG.IDU} AND M.ID_Destinatario = ${activeChatID}) 
                        OR (M.ID_Remitente = ${activeChatID} AND M.ID_Destinatario = ${CONFIG.IDU}) 
                     ORDER BY M.TimeStamp ASC`;
        const res = await api(sql, 'SELECT');
        renderMessages(res.data);
    }

    async function sendMessage() {
        const txt = UI.input.value.trim();
        if(!txt || activeChatID === 0) return;
        UI.input.value = ''; 
        const sql = `INSERT INTO Chat_Mensajes (IDU, ID_Remitente, ID_Destinatario, Mensaje) 
                     VALUES (${CONFIG.IDU}, ${CONFIG.IDU}, ${activeChatID}, '${txt}')`;
        await api(sql, 'EXECUTE');
        loadMessages();
    }

    // --- RENDER (MODIFICADO: Prioriza Foto_Thumb) ---

    function renderList(data) {
        if(!data || data.length === 0) {
            UI.listArea.innerHTML = '<div class="text-center p-3 text-muted">No encontrado</div>';
            return;
        }

        let html = '';
        data.forEach(u => {
            // LÓGICA DE IMAGEN: Si existe en BD la usa, si no, usa la default del sistema
            let img = (u.Foto_Thumb && u.Foto_Thumb.length > 50) ? u.Foto_Thumb : CONFIG.DEF_IMG;
            let time = u.UltimoMsg ? new Date(u.UltimoMsg.replace(/-/g,"/")).toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'}) : '';

            html += `
            <div class="media userlist-box waves-effect waves-light" 
                 style="cursor:pointer; border-bottom:1px solid #f1f1f1;"
                 onclick="ChatSystem.goChat(${u.IDU}, '${u.Nombre}')">
                <a class="media-left" href="#!">
                    <img class="media-object img-radius" src="${img}" alt="User" 
                         style="width:40px; height:40px; object-fit:cover;"
                         onerror="this.src='${CONFIG.DEF_IMG}'">
                    <div class="live-status bg-success"></div>
                </a>
                <div class="media-body">
                    <div class="chat-header" style="font-size:14px; font-weight:600;">${u.Nombre}</div>
                    <div style="font-size:11px; color:#999;">${time}</div>
                </div>
            </div>`;
        });
        UI.listArea.innerHTML = html;
    }

    function renderMessages(data) {
        if(!data || data.length === 0) {
            UI.msgArea.innerHTML = '<div class="text-center mt-5 text-muted">Saluda...</div>';
            return;
        }

        let html = '';
        data.forEach(m => {
            let isMe = (m.ID_Remitente == CONFIG.IDU);
            let time = new Date(m.TimeStamp.replace(/-/g,"/")).toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'});
            
            // IMAGEN DINÁMICA: Traída por el JOIN en loadMessages
            let img = (m.Foto_Thumb && m.Foto_Thumb.length > 50) ? m.Foto_Thumb : CONFIG.DEF_IMG;

            if (isMe) {
                html += `
                <div class="media chat-messages">
                    <div class="media-body chat-menu-reply">
                        <div><p class="chat-cont">${m.Mensaje}</p></div>
                        <p class="chat-time">${time}</p>
                    </div>
                </div>`;
            } else {
                html += `
                <div class="media chat-messages">
                    <a class="media-left photo-table" href="#!">
                        <img class="media-object img-radius m-t-5" src="${img}" alt="User" 
                             style="width:35px; height:35px; object-fit:cover;"
                             onerror="this.src='${CONFIG.DEF_IMG}'">
                    </a>
                    <div class="media-body chat-menu-content">
                        <div><p class="chat-cont">${m.Mensaje}</p></div>
                        <p class="chat-time">${time}</p>
                    </div>
                </div>`;
            }
        });
        
        UI.msgArea.innerHTML = html;
        UI.msgArea.scrollTop = UI.msgArea.scrollHeight;
    }

    async function api(sql, type) {
        let fd = new FormData();
        fd.append('sql', sql);
        fd.append('db', CONFIG.DB);
        try {
            let req = await fetch(CONFIG.URL_AJAX + (type === 'SELECT' ? 'Select.php' : 'Execute.php'), { method: 'POST', body: fd });
            return await req.json();
        } catch(e) { return {data:[]}; }
    }

    function startPolling() { if(poller) clearInterval(poller); poller = setInterval(loadMessages, 3000); }
    function stopPolling() { if(poller) clearInterval(poller); }

    return { init: init, goChat: openChat };
})();

if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', ChatSystem.init);
else ChatSystem.init();
</script>