(function (){
'use strict';
var CFG=window.ELX_CHAT||{};
var NONCE=CFG.nonce||'';
function endpoint(){
return (CFG.endpoint||'/wp-admin/admin-ajax.php') + '?action=elixie_chat&nonce=' + encodeURIComponent(NONCE);
}
function refreshNonce(){
return fetch('/wp-json/elixie/v1/nonce', { cache: 'no-store' })
.then(function (r){ return r.json(); })
.then(function (d){ if(d&&d.nonce) NONCE=d.nonce; });
}
var isOpen=false;
var isLoading=false;
var history=[];
var leadTracked=false;
var sessionId='';
try {
sessionId=localStorage.getItem('elx_chat_session')||'';
if(!sessionId){
sessionId='elx-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 10);
localStorage.setItem('elx_chat_session', sessionId);
}} catch (e){ sessionId='elx-mem-' + Math.random().toString(36).slice(2, 12); }
var GREETING='¡Hola! Soy Lía, tu asesora de Elixie. 💜\n\n¿Buscas hidratar tu piel, tienes dudas del sérum o de tu envío? Cuéntame y te ayudo a elegir.';
var SUGGESTIONS=[
'¿Qué pack me conviene?',
'¿Para qué sirve el sérum?',
'¿Cómo se aplica?',
'Quiero hablar con una persona'
];
var bubble=document.getElementById('elx-chat-bubble');
var panel=document.getElementById('elx-chat-panel');
var messages=document.getElementById('elx-chat-messages');
var typingEl=document.getElementById('elx-chat-typing');
var inputEl=document.getElementById('elx-chat-input');
var sendBtn=document.getElementById('elx-chat-send');
var closeBtn=document.getElementById('elx-chat-close');
var dot=document.getElementById('elx-chat-dot');
if(!bubble) return;
function openChat(){
isOpen=true;
panel.classList.add('is-open');
bubble.setAttribute('aria-expanded', 'true');
document.getElementById('elx-bubble-icon-chat').style.display='none';
document.getElementById('elx-bubble-icon-close').style.display='';
dot.classList.remove('visible');
if(!messages.children.length){
appendBot(GREETING);
showSuggestions(SUGGESTIONS);
}
setTimeout(function (){ inputEl.focus(); }, 150);
}
function closeChat(){
isOpen=false;
panel.classList.remove('is-open');
bubble.setAttribute('aria-expanded', 'false');
document.getElementById('elx-bubble-icon-chat').style.display='';
document.getElementById('elx-bubble-icon-close').style.display='none';
}
bubble.addEventListener('click', function (){ isOpen ? closeChat():openChat(); });
closeBtn.addEventListener('click', closeChat);
document.addEventListener('keydown', function (e){ if(e.key==='Escape'&&isOpen) closeChat(); });
setTimeout(function (){ if(!isOpen) dot.classList.add('visible'); }, 20000);
function showSuggestions(items){
removeSuggestions();
var wrap=document.createElement('div');
wrap.className='elx-suggestions';
items.forEach(function (text){
var btn=document.createElement('button');
btn.className='elx-suggestion-btn';
btn.textContent=text;
btn.addEventListener('click', function (){ removeSuggestions(); sendMessage(text); });
wrap.appendChild(btn);
});
messages.appendChild(wrap);
scrollBottom();
}
function removeSuggestions(){
var nodes=messages.querySelectorAll('.elx-suggestions');
for (var i=0; i < nodes.length; i++) nodes[i].remove();
}
function appendBot(text, isError){
removeSuggestions();
var wrap=document.createElement('div');
wrap.className='elx-msg elx-msg-bot' + (isError ? ' elx-msg-error':'');
var av=document.createElement('div');
av.className='elx-msg-avatar';
av.textContent='L';
var body=document.createElement('div');
body.className='elx-msg-body';
body.innerHTML=renderMd(text);
wrap.appendChild(av);
wrap.appendChild(body);
messages.appendChild(wrap);
scrollBottom();
}
function appendUser(text){
var wrap=document.createElement('div');
wrap.className='elx-msg elx-msg-user';
var body=document.createElement('div');
body.className='elx-msg-body';
body.textContent=text;
wrap.appendChild(body);
messages.appendChild(wrap);
scrollBottom();
}
function scrollBottom(){ messages.scrollTop=messages.scrollHeight; }
function renderMd(text){
return text
.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>')
.replace(/\n/g, '<br>');
}
function showTyping(){ typingEl.style.display='flex'; scrollBottom(); }
function hideTyping(){ typingEl.style.display='none'; }
function sendMessage(text){
var msg=(text||inputEl.value).trim();
if(!msg||isLoading) return;
if(!leadTracked&&window.elxTrack){ window.elxTrack('chat_lead'); leadTracked=true; }
removeSuggestions();
appendUser(msg);
inputEl.value='';
autoResize();
sendBtn.disabled=true;
isLoading=true;
showTyping();
doSend(msg, true);
}
function doSend(msg, allowRetry){
fetch(endpoint(), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: msg,
history: history,
session_id: sessionId,
page_url: window.location.href,
page_title: document.title
})
})
.then(function (res){
if(res.status===403&&allowRetry){
return refreshNonce().then(function (){ doSend(msg, false); return null; });
}
return res.json().catch(function (){ return { error: 'Error inesperado.' };});
})
.then(function (data){
if(data===null) return;
hideTyping();
isLoading=false;
if(data.error){ appendBot('⚠ ' + data.error, true); return; }
var reply=data.reply||'';
appendBot(reply);
history.push({ role: 'user', content: msg });
history.push({ role: 'assistant', content: reply });
if(history.length > 40) history=history.slice(-40);
})
.catch(function (){
hideTyping();
isLoading=false;
appendBot('Error de red. Intenta de nuevo.', true);
});
}
inputEl.addEventListener('input', function (){
sendBtn.disabled = !inputEl.value.trim();
autoResize();
});
inputEl.addEventListener('keydown', function (e){
if(e.key==='Enter'&&!e.shiftKey){
e.preventDefault();
if(!sendBtn.disabled) sendMessage();
}});
sendBtn.addEventListener('click', function (){ sendMessage(); });
function autoResize(){
inputEl.style.height='auto';
inputEl.style.height=Math.min(inputEl.scrollHeight, 120) + 'px';
}})();