<div id="ai-chat-wrapper" style="position: fixed; bottom: 20px; left: 20px; z-index: 9999;">
<div id="ai-chat-wrapper" style="position: fixed; bottom: 20px; left: 20px; z-index: 9999;">
    <!-- Botón tipo Píldora para diferenciarlo de un chat normal -->
    <button id="ai-chat-toggle" class="btn btn-primary shadow-lg d-flex align-items-center px-3" style="border-radius: 30px; height: 50px; border: 2px solid rgba(255,255,255,0.3); background: linear-gradient(135deg, #007bff, #6610f2); transition: all 0.3s ease;">
        <div style="width: 35px; height: 35px; border-radius: 50%; overflow: hidden; margin-right: 10px; border: 1px solid white;">
            <img src="https://d7keiwzj12p9.cloudfront.net/chatbubbles/Gemini_Generated_Image_sfcoe9sfcoe9sfco-1742599731241.webp" style="width: 100%; height: 100%; object-fit: cover;">
        </div>
        <span class="text-white font-weight-bold" style="font-size: 0.9rem; letter-spacing: 0.5px;">MODO IA: ANÁLISIS CLÍNICO</span>
        <div class="ml-2" style="width: 8px; height: 8px; background: #28a745; border-radius: 50%; box-shadow: 0 0 5px #28a745; animation: pulse 2s infinite;"></div>
    </button>

    <div id="ai-chat-window" class="card shadow-lg d-none" style="position: absolute; bottom: 65px; left: 0; width: 380px; height: 550px; display: flex; flex-direction: column; border-radius: 20px; overflow: hidden; border: 1px solid rgba(0,0,0,0.15);">
        <div class="card-header text-white d-flex justify-content-between align-items-center" style="background: linear-gradient(135deg, #007bff, #6610f2) !important; padding: 15px;">
            <div class="d-flex align-items-center">
                <div style="position: relative;">
                    <img src="https://d7keiwzj12p9.cloudfront.net/chatbubbles/Gemini_Generated_Image_sfcoe9sfcoe9sfco-1742599731241.webp" style="width: 40px; height: 40px; border-radius: 50%; margin-right: 12px; border: 2px solid white;">
                    <div style="position: absolute; bottom: 2px; right: 12px; width: 10px; height: 10px; background: #28a745; border-radius: 50%; border: 2px solid white;"></div>
                </div>
                <div>
                    <h6 class="m-0 font-weight-bold">Sophia Intelligence</h6>
                    <small style="opacity: 0.8;">Acceso a Datos en Tiempo Real</small>
                </div>
            </div>
            <button type="button" class="close text-white" id="ai-chat-close" style="outline: none; background: transparent; border: 0; font-size: 1.5rem;">&times;</button>
        </div>
        <div class="card-body" id="ai-chat-messages" style="overflow-y: auto; flex-grow: 1; background: #f8f9fa; display: flex; flex-direction: column; padding: 20px;">
            <div class="chat-msg msg-ai shadow-sm">
                <strong>Hola, soy la Dra. Sophia.</strong><br>
                He activado el <strong>Modo de Inteligencia Clínica</strong>. A diferencia de mi chat de soporte, aquí tengo acceso directo a tus pacientes, citas e historias clínicas para realizar análisis avanzados. ¿Qué dato necesitas procesar hoy?
            </div>
        </div>
        <div class="card-footer bg-white p-3 border-top-0">
            <div class="input-group shadow-sm" style="border-radius: 25px; overflow: hidden; border: 1px solid #dee2e6;">
                <input type="text" id="ai-chat-input" class="form-control border-0" placeholder="Ej: Resumen de Pedro Garcia..." style="box-shadow: none; padding-left: 20px; height: 45px;">
                <div class="input-group-append">
                    <button class="btn btn-link text-primary px-3" id="ai-chat-send" style="text-decoration: none;">
                        <i class="fas fa-paper-plane"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    @keyframes pulse { 0% { transform: scale(0.95); opacity: 0.7; } 70% { transform: scale(1.1); opacity: 1; } 100% { transform: scale(0.95); opacity: 0.7; } }
    .chat-msg { margin-bottom: 15px; padding: 12px 16px; border-radius: 15px; max-width: 88%; font-size: 0.9rem; line-height: 1.5; position: relative; }
    .msg-user { background: #007bff; color: white; align-self: flex-end; border-bottom-right-radius: 2px; }
    .msg-ai { background: white; color: #333; align-self: flex-start; border-bottom-left-radius: 2px; border: 1px solid #eee; }
    #ai-chat-messages::-webkit-scrollbar { width: 5px; }
    #ai-chat-messages::-webkit-scrollbar-thumb { background: #ddd; border-radius: 10px; }
</style>
        <div class="card-footer bg-white p-2">
            <div class="input-group">
                <input type="text" id="ai-chat-input" class="form-control border-0" placeholder="Escribe tu pregunta..." style="box-shadow: none;">
                <div class="input-group-append">
                    <button class="btn btn-link text-primary" id="ai-chat-send">
                        <i class="fas fa-paper-plane"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    .chat-msg { margin-bottom: 12px; padding: 10px 15px; border-radius: 18px; max-width: 85%; font-size: 0.85rem; line-height: 1.4; position: relative; box-shadow: 0 1px 2px rgba(0,0,0,0.1); }
    .msg-user { background: #007bff; color: white; align-self: flex-end; border-bottom-right-radius: 2px; }
    .msg-ai { background: white; color: #333; align-self: flex-start; border-bottom-left-radius: 2px; }
    #ai-chat-messages::-webkit-scrollbar { width: 4px; }
    #ai-chat-messages::-webkit-scrollbar-thumb { background: #ccc; border-radius: 10px; }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const toggle = document.getElementById('ai-chat-toggle');
    const windowChat = document.getElementById('ai-chat-window');
    const close = document.getElementById('ai-chat-close');
    const input = document.getElementById('ai-chat-input');
    const send = document.getElementById('ai-chat-send');
    const container = document.getElementById('ai-chat-messages');

    if (!toggle || !windowChat) return;

    toggle.onclick = () => {
        windowChat.classList.toggle('d-none');
        if (!windowChat.classList.contains('d-none')) input.focus();
    };
    
    close.onclick = () => windowChat.classList.add('d-none');

    function appendMessage(text, type) {
        const div = document.createElement('div');
        div.className = 'chat-msg ' + (type === 'user' ? 'msg-user' : 'msg-ai');
        div.innerText = text;
        container.appendChild(div);
        container.scrollTop = container.scrollHeight;
    }

    let chatHistory = [];

    async function sendMessage() {
        const msg = input.value.trim();
        if (!msg) return;

        appendMessage(msg, 'user');
        chatHistory.push({ role: 'user', content: msg });
        input.value = '';
        
        const loading = document.createElement('div');
        loading.className = 'chat-msg msg-ai';
        loading.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Consultando base de datos...';
        container.appendChild(loading);
        container.scrollTop = container.scrollHeight;

        try {
            const response = await fetch('/api/chat', {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || ''
                },
                body: JSON.stringify({ 
                    message: msg,
                    history: chatHistory 
                })
            });
            const data = await response.json();
            if (loading.parentNode) container.removeChild(loading);
            
            const reply = data.reply || 'No obtuve respuesta.';
            appendMessage(reply, 'ai');
            chatHistory.push({ role: 'assistant', content: reply });

            // Mantener solo los últimos 14 mensajes para contexto
            if (chatHistory.length > 14) {
                chatHistory.splice(0, 2);
            }
        } catch (e) {
            if(loading.parentNode) container.removeChild(loading);
            appendMessage('Error de conexión con el servidor.', 'ai');
        }
    }

    send.onclick = sendMessage;
    input.onkeypress = (e) => { if(e.key === 'Enter') sendMessage(); };
});
</script>
