/**
* ai-chat-widget.js - Tutor Virtual UdeCi (UniCABA)
* Experiencia de usuario y diseño tipo Bottom Sheet móvil estilo Mercado Libre.
* Incluye soporte RAG, input dock inteligente, manejo de teclado virtual,
* chips de rol, copia de mensajes y síntesis de voz en español.
*/
(function () {
'use strict';
let isProcessing = false;
let touchStartY = 0;
let touchDeltaY = 0;
// Limpiar claves obsoletas
try {
sessionStorage.removeItem('edu_space_udeci_chat_history_v2');
localStorage.removeItem('edu_space_udeci_chat_history_v2');
} catch (e) { }
function getContainer() {
return document.getElementById('aiChatContainer');
}
function getUserId() {
const container = getContainer();
const rawId = container ? (container.getAttribute('data-user-id') || container.getAttribute('data-user-email')) : null;
if (rawId && rawId.toString().trim()) {
return 'usr_' + rawId.toString().trim().replace(/[^a-zA-Z0-9_-]/g, '_');
}
let anonId = sessionStorage.getItem('edu_space_anon_chat_session');
if (!anonId) {
anonId = 'anon_' + Math.random().toString(36).substring(2, 10) + '_' + Date.now();
sessionStorage.setItem('edu_space_anon_chat_session', anonId);
}
return anonId;
}
function getStorageKey() {
return 'edu_space_udeci_chat_usr_' + getUserId();
}
function getUserRole() {
const container = getContainer();
const rawRole = (container ? container.getAttribute('data-user-role') : 'alumno') || 'alumno';
const r = rawRole.toLowerCase();
if (r === 'admin' || r.includes('admin')) return 'admin';
if (r.includes('bedelia')) return 'bedelia';
if (r.includes('docente') || r.includes('profesor') || r.includes('teacher')) return 'docente';
return 'alumno';
}
function getUserName() {
const container = getContainer();
return (container ? container.getAttribute('data-user-name') : '') || '';
}
function getRawUserId() {
const container = getContainer();
return (container ? container.getAttribute('data-user-id') : '') || '';
}
function getUserEmail() {
const container = getContainer();
return (container ? container.getAttribute('data-user-email') : '') || '';
}
function getWelcomeMessage(role, name) {
const greeting = name ? `¡Hola, ${name}!` : '¡Hola!';
return `## ${greeting}\n¿Cómo puedo ayudarte?`;
}
function getDefaultOptions(role) {
const r = (role || '').toLowerCase();
if (r.includes('alumno') || r.includes('estudiante')) {
return [
"¿Dónde curso hoy y qué aula me toca?",
"¿Cuáles son mis calificaciones y notas?",
"¿Qué convenios y descuentos tengo vigentes?"
];
} else if (r.includes('docente') || r.includes('profesor') || r.includes('teacher')) {
return [
"¿Qué comisiones y horarios tengo asignados hoy?",
"¿Cómo registro calificaciones en el acta?",
"¿Cómo solicitar una nueva reserva de aula?"
];
} else if (r.includes('bedelia')) {
return [
"¿Cuáles son los 9 pasos del flujo de Bedelía?",
"¿Cómo resuelvo un conflicto áulico o de aforo?",
"¿Cómo agrego un nuevo convenio o beneficio?"
];
} else if (r.includes('recepcion')) {
return [
"¿Cómo verificar una credencial digital QR?",
"¿Cómo buscar a un alumno por documento?",
"¿Cómo consultar las clases presenciales de hoy?"
];
} else {
return [
"¿Cómo agrego un nuevo convenio comercial?",
"¿Cómo funciona el escáner de recepción QR?",
"¿Cómo optimizar aulas con el algoritmo genético?"
];
}
}
function loadHistory() {
try {
const raw = sessionStorage.getItem(getStorageKey());
return raw ? JSON.parse(raw) : [];
} catch (e) {
return [];
}
}
function saveHistory(messages) {
try {
sessionStorage.setItem(getStorageKey(), JSON.stringify(messages));
} catch (e) { }
}
function renderMarkdown(text) {
if (!text) return '';
// Proteger enlaces Markdown [texto](url)
const links = [];
let processed = text.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g, (match, label, url) => {
const idx = links.length;
links.push({ label, url });
return `__MD_LINK_${idx}__`;
});
// Proteger URLs directas https://...
const rawUrls = [];
processed = processed.replace(/(https?:\/\/[^\s<"'>)]+)/g, (match, url) => {
const idx = rawUrls.length;
rawUrls.push(url);
return `__RAW_URL_${idx}__`;
});
// Escaping seguro de HTML
let escaped = processed
.replace(/&/g, '&')
.replace(//g, '>');
// Negrita **texto**
escaped = escaped.replace(/\*\*(.*?)\*\*/g, '$1');
// Cursiva *texto*
escaped = escaped.replace(/\*(.*?)\*/g, '$1');
// Código inline `codigo`
escaped = escaped.replace(/`([^`]+)`/g, '$1');
// Saltos de línea
escaped = escaped.replace(/\n/g, '
');
// Restaurar enlaces Markdown como botones atractivos
escaped = escaped.replace(/__MD_LINK_(\d+)__/g, (match, idx) => {
const item = links[parseInt(idx, 10)];
if (!item) return '';
return `${item.label}`;
});
// Restaurar URLs directas como enlaces clickeables
escaped = escaped.replace(/__RAW_URL_(\d+)__/g, (match, idx) => {
const url = rawUrls[parseInt(idx, 10)];
if (!url) return '';
const displayUrl = url.length > 46 ? url.substring(0, 43) + '...' : url;
return `${displayUrl}`;
});
return escaped;
}
function formatCurrentTime() {
const now = new Date();
return now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
function appendMessage(role, content, options = [], save = true, timeStr = null) {
const messagesContainer = document.getElementById('aiChatMessages');
if (!messagesContainer) return;
const isUser = role === 'user';
const msgDiv = document.createElement('div');
msgDiv.className = `ai-msg ${isUser ? 'ai-msg-user' : 'ai-msg-assistant'}`;
const formattedHtml = renderMarkdown(content);
const timestamp = timeStr || formatCurrentTime();
if (isUser) {
msgDiv.innerHTML = `
${formattedHtml}
${timestamp}
`;
} else {
let optionsHtml = '';
if (options && options.length > 0) {
optionsHtml = '';
options.forEach(opt => {
let iconClass = 'bi-chat-left-dots';
const optLower = opt.toLowerCase();
if (optLower.includes('aula') || optLower.includes('curso') || optLower.includes('donde') || optLower.includes('espacio')) iconClass = 'bi-door-closed';
else if (optLower.includes('nota') || optLower.includes('calificaci') || optLower.includes('acta')) iconClass = 'bi-award';
else if (optLower.includes('descuento') || optLower.includes('beneficio') || optLower.includes('convenio')) iconClass = 'bi-tag';
else if (optLower.includes('reserva') || optLower.includes('horario') || optLower.includes('clase')) iconClass = 'bi-calendar3';
else if (optLower.includes('qr') || optLower.includes('credencial') || optLower.includes('verificar') || optLower.includes('documento')) iconClass = 'bi-qr-code';
else if (optLower.includes('paso') || optLower.includes('flujo') || optLower.includes('bedelia') || optLower.includes('genetico')) iconClass = 'bi-diagram-3';
optionsHtml += ``;
});
optionsHtml += '
';
}
msgDiv.innerHTML = `
${formattedHtml}
${optionsHtml}
`;
// Configurar botones de acción interactivos estilo Mercado Libre
const copyBtn = msgDiv.querySelector('.copy-btn');
if (copyBtn) {
copyBtn.addEventListener('click', () => {
const temp = document.createElement('div');
temp.innerHTML = formattedHtml;
const plain = temp.textContent || temp.innerText || '';
if (navigator.clipboard) {
navigator.clipboard.writeText(plain).then(() => {
copyBtn.innerHTML = '';
setTimeout(() => { copyBtn.innerHTML = ''; }, 2000);
});
}
});
}
const speakBtn = msgDiv.querySelector('.speak-btn');
if (speakBtn) {
speakBtn.addEventListener('click', () => {
if ('speechSynthesis' in window) {
if (window.speechSynthesis.speaking) {
window.speechSynthesis.cancel();
speakBtn.classList.remove('active');
return;
}
const temp = document.createElement('div');
temp.innerHTML = formattedHtml;
const plain = temp.textContent || temp.innerText || '';
const utter = new SpeechSynthesisUtterance(plain);
utter.lang = 'es-AR';
speakBtn.classList.add('active');
utter.onend = () => speakBtn.classList.remove('active');
utter.onerror = () => speakBtn.classList.remove('active');
window.speechSynthesis.speak(utter);
}
});
}
const thumbsUp = msgDiv.querySelector('.thumbs-up-btn');
const thumbsDown = msgDiv.querySelector('.thumbs-down-btn');
if (thumbsUp && thumbsDown) {
thumbsUp.addEventListener('click', () => {
thumbsUp.classList.toggle('active');
thumbsDown.classList.remove('active');
});
thumbsDown.addEventListener('click', () => {
thumbsDown.classList.toggle('active');
thumbsUp.classList.remove('active');
});
}
}
messagesContainer.appendChild(msgDiv);
messagesContainer.scrollTop = messagesContainer.scrollHeight;
// Asignar listeners a los chips de opciones
msgDiv.querySelectorAll('.ai-option-btn').forEach(btn => {
btn.addEventListener('click', function (e) {
e.preventDefault();
const q = this.getAttribute('data-query');
if (q) sendQuery(q);
});
});
if (save) {
const history = loadHistory();
history.push({ role, content, options, timeStr: timestamp });
saveHistory(history);
}
}
function closeChat() {
const panel = document.getElementById('aiChatPanel');
const backdrop = document.getElementById('aiChatBackdrop');
const launcher = document.getElementById('aiChatLauncher');
if (panel) {
panel.classList.add('d-none');
panel.style.transform = '';
panel.style.height = '';
panel.style.bottom = '';
}
if (backdrop) backdrop.classList.add('d-none');
if (launcher) launcher.classList.remove('chat-open');
document.body.classList.remove('ai-chat-mobile-open');
if ('speechSynthesis' in window && window.speechSynthesis.speaking) {
window.speechSynthesis.cancel();
}
}
async function sendQuery(queryText) {
if (!queryText || isProcessing) return;
const textarea = document.getElementById('aiChatInput');
const typing = document.getElementById('aiChatTyping');
const sendBtn = document.getElementById('aiChatSendBtn');
if (textarea) textarea.value = '';
appendMessage('user', queryText, [], true);
isProcessing = true;
if (typing) typing.classList.remove('d-none');
if (sendBtn) sendBtn.disabled = true;
const userRole = getUserRole();
const userName = getUserName();
const rawUserId = getRawUserId();
const userEmail = getUserEmail();
const rawHistory = loadHistory();
const payloadMessages = rawHistory.map(m => ({
role: m.role,
content: m.content
}));
try {
const res = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
messages: payloadMessages,
user_role: userRole,
user_name: userName,
user_id: rawUserId || null,
user_email: userEmail || null,
current_path: window.location.pathname,
conversation_id: getUserId()
})
});
if (!res.ok) {
throw new Error(`Error HTTP ${res.status}`);
}
const data = await res.json();
const reply = data.response || data.reply || "Disculpa, no pude procesar tu solicitud en este momento.";
const options = Array.isArray(data.quick_options) ? data.quick_options : (Array.isArray(data.options) ? data.options : []);
appendMessage('assistant', reply, options, true);
if (data.guide_step && window.WalkthroughEngine) {
closeChat();
window.WalkthroughEngine.startStep(data.guide_step);
}
} catch (err) {
console.error("[UdeCi Widget] Error al consultar API:", err);
appendMessage('assistant', "Hubo una interrupción en la conexión con el tutor inteligente. Por favor, verifica tu conexión o intenta nuevamente en unos instantes.", [], true);
} finally {
isProcessing = false;
if (typing) typing.classList.add('d-none');
if (sendBtn) sendBtn.disabled = false;
if (textarea && window.innerWidth > 768) textarea.focus();
}
}
function initChat() {
const launcher = document.getElementById('aiChatLauncher');
const panel = document.getElementById('aiChatPanel');
const backdrop = document.getElementById('aiChatBackdrop');
const backBtn = document.getElementById('aiChatBackBtn');
const closeBtn = document.getElementById('aiChatCloseBtn');
const clearBtn = document.getElementById('aiChatClearBtn');
const plusBtn = document.getElementById('aiChatPlusBtn');
const textarea = document.getElementById('aiChatInput');
const handleBar = document.getElementById('aiSheetHandleBar');
if (!launcher || !panel) return;
const role = getUserRole();
const name = getUserName();
function openChat() {
panel.classList.remove('d-none');
if (backdrop) backdrop.classList.remove('d-none');
launcher.classList.add('chat-open');
if (window.innerWidth <= 768) {
document.body.classList.add('ai-chat-mobile-open');
}
setTimeout(() => {
const messagesContainer = document.getElementById('aiChatMessages');
if (messagesContainer) messagesContainer.scrollTop = messagesContainer.scrollHeight;
if (textarea && window.innerWidth > 768) textarea.focus();
}, 100);
}
// Toggle panel
launcher.addEventListener('click', () => {
const isHidden = panel.classList.contains('d-none');
if (isHidden) openChat(); else closeChat();
});
if (backBtn) backBtn.addEventListener('click', closeChat);
if (closeBtn) closeBtn.addEventListener('click', closeChat);
if (backdrop) backdrop.addEventListener('click', closeChat);
// Deslizar hacia abajo en la drag handle bar para cerrar (Touch Gesture)
if (handleBar) {
handleBar.addEventListener('touchstart', (e) => {
touchStartY = e.touches[0].clientY;
touchDeltaY = 0;
}, { passive: true });
handleBar.addEventListener('touchmove', (e) => {
touchDeltaY = e.touches[0].clientY - touchStartY;
if (touchDeltaY > 0) {
panel.style.transform = `translateY(${touchDeltaY}px)`;
}
}, { passive: true });
handleBar.addEventListener('touchend', () => {
if (touchDeltaY > 65) {
closeChat();
} else {
panel.style.transform = '';
}
touchDeltaY = 0;
});
}
// Botón + enfoca el campo de entrada
if (plusBtn && textarea) {
plusBtn.addEventListener('click', () => {
textarea.focus();
});
}
// Manejo del Teclado Virtual en Dispositivos Móviles (visualViewport)
if (window.visualViewport) {
window.visualViewport.addEventListener('resize', () => {
if (window.innerWidth <= 768 && !panel.classList.contains('d-none')) {
const currentViewHeight = window.visualViewport.height;
const screenHeight = window.innerHeight;
// Si la altura del viewport se reduce significativamente (teclado abierto)
if (currentViewHeight < screenHeight * 0.88) {
panel.style.height = `${currentViewHeight}px`;
panel.style.bottom = `${Math.max(0, screenHeight - currentViewHeight - (window.visualViewport.offsetTop || 0))}px`;
} else {
// Teclado cerrado
panel.style.height = '';
panel.style.bottom = '';
}
const messagesContainer = document.getElementById('aiChatMessages');
if (messagesContainer) {
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
}
});
}
// Escape para cerrar
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && panel && !panel.classList.contains('d-none')) {
closeChat();
}
});
// Reiniciar conversación
if (clearBtn) {
clearBtn.addEventListener('click', () => {
sessionStorage.removeItem(getStorageKey());
const messagesContainer = document.getElementById('aiChatMessages');
if (messagesContainer) messagesContainer.innerHTML = '';
appendMessage('assistant', getWelcomeMessage(role, name), getDefaultOptions(role), false);
});
}
// Cargar historial previo o bienvenida con sugerencias
const history = loadHistory();
if (history.length > 0) {
history.forEach(msg => appendMessage(msg.role, msg.content, msg.options || [], false, msg.timeStr));
} else {
appendMessage('assistant', getWelcomeMessage(role, name), getDefaultOptions(role), false);
}
// Atajo Enter en desktop
if (textarea) {
textarea.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
window.handleAiChatSubmit(e);
}
});
}
}
window.handleAiChatSubmit = function (e) {
if (e) e.preventDefault();
const textarea = document.getElementById('aiChatInput');
if (!textarea) return;
const text = textarea.value.trim();
if (text) sendQuery(text);
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initChat);
} else {
initChat();
}
})();