(function (){
'use strict';
let chatHistory=[];
let userName='';
let userEmail='';
let userPhone='';
let chatSessionId='';
let dynamicFieldsData={};
const LS_KEY_NAME='scs_chat_userName';
const LS_KEY_EMAIL='scs_chat_userEmail';
const LS_KEY_PHONE='scs_chat_userPhone';
const LS_KEY_DYNAMIC='scs_chat_dynamicFields';
const LS_KEY_HISTORY='scs_chat_history';
const LS_KEY_CHAT_ID='scs_chat_sessionId';
const LS_KEY_EXPIRY='scs_chat_expiry';
const MAX_AGE_MS=2 * 24 * 60 * 60 * 1000;
let utmParams={};
let referrer='';
let selectedFiles=[];
function init(){
scsUi.init();
scsAccessibility.init();
if(typeof scsConfig!=='undefined'&&scsConfig.showNewChatButton!=='1'){
const elements=scsUi.getElements();
if(elements.newChatBtn){
elements.newChatBtn.style.setProperty('display', 'none', 'important');
}}
utmParams=scsUtils.getUtmParams();
referrer=scsUtils.getReferrer();
const elements=scsUi.getElements();
if(!checkLocalStorage()){
clearLocalStorage();
}
if(elements.startForm){
elements.startForm.addEventListener('submit', handleNewChatSubmit);
}
if(elements.sendBtn){
elements.sendBtn.addEventListener('click', sendMessage);
}
if(elements.userInput){
elements.userInput.addEventListener('keydown', (e)=> {
if(e.key==='Enter'&&!e.shiftKey){
const enterSends=localStorage.getItem('scs_accessibility_enter_sends');
const shouldSend=enterSends!==null ? enterSends==='true':scsConfig.accessibilityEnterSends==='1';
if(shouldSend){
e.preventDefault();
sendMessage();
}}
});
}
if(elements.newChatBtn){
elements.newChatBtn.addEventListener('click', ()=> {
elements.chatInterface.style.display='none';
elements.startFormContainer.style.display='flex';
elements.chatContainer.innerHTML='';
chatHistory=[];
clearLocalStorage();
});
}
if(elements.fileInputHidden){
elements.fileInputHidden.accept=scsConfig.allowedTypes.split(',').map(t=> '.' + t.trim()).join(',');
elements.fileInputHidden.addEventListener('change', handleFileSelect);
}
document.addEventListener('scs-remove-selected-file', removeSelectedFile);
}
function checkInputAndToggleSendButton(){
const elements=scsUi.getElements();
if(elements.userInput&&elements.sendBtn){
const hasText=elements.userInput.value.trim().length > 0;
const hasFiles=selectedFiles.length > 0;
elements.sendBtn.disabled = !(hasText||hasFiles);
}}
function setupAttachmentLogic(){
}
function handleFileSelect(e){
const newFiles=Array.from(e.target.files);
if(newFiles.length===0) return;
const maxTotal=scsConfig.maxAttachments||5;
const allowed=scsConfig.allowedTypes.split(',').map(t=> t.trim().toLowerCase());
const maxSize=scsConfig.maxFileSize * 1024 * 1024;
for (const file of newFiles){
if(selectedFiles.length >=maxTotal){
alert(scsUtils.__('maxFilesReached', { n: maxTotal }));
break;
}
const ext=file.name.split('.').pop().toLowerCase();
if(!allowed.includes(ext)){
alert(scsUtils.__('invalidFileType', { ext: ext, name: file.name }));
continue;
}
if(file.size > maxSize){
alert(scsUtils.__('fileTooLarge', { name: file.name, size: scsConfig.maxFileSize }));
continue;
}
selectedFiles.push(file);
}
e.target.value='';
scsUi.updateFilePreviews(selectedFiles, removeSelectedFile);
scsUi.checkInputAndToggleSendButton();
}
function removeSelectedFile(index){
selectedFiles.splice(index, 1);
scsUi.updateFilePreviews(selectedFiles, removeSelectedFile);
scsUi.checkInputAndToggleSendButton();
}
function renderFilePreview(){
}
function checkLocalStorage(){
if(typeof (Storage)==="undefined") return false;
const expiryTime=localStorage.getItem(LS_KEY_EXPIRY);
if(!expiryTime) return false;
const now=new Date().getTime();
if((now - parseInt(expiryTime, 10)) > MAX_AGE_MS) return false;
userName=localStorage.getItem(LS_KEY_NAME);
userEmail=localStorage.getItem(LS_KEY_EMAIL);
if(userName&&userEmail){
userPhone=localStorage.getItem(LS_KEY_PHONE)||'';
const historyJson=localStorage.getItem(LS_KEY_HISTORY);
const dynamicJson=localStorage.getItem(LS_KEY_DYNAMIC);
if(historyJson){
try { chatHistory=JSON.parse(historyJson); } catch (e){ chatHistory=[]; }}
if(dynamicJson){
try { dynamicFieldsData=JSON.parse(dynamicJson); } catch (e){ dynamicFieldsData={};}}
chatSessionId=localStorage.getItem(LS_KEY_CHAT_ID)||'';
loadStoredDataToUI();
scsUi.getElements().startFormContainer.style.setProperty('display', 'none', 'important');
scsUi.getElements().chatInterface.style.display='flex';
loadChatHistory();
return true;
}
return false;
}
function loadStoredDataToUI(){
const elements=scsUi.getElements();
Object.keys(dynamicFieldsData).forEach(name=> {
const inputs=document.querySelectorAll(`[name="${name}"], [name="${name}[]"], #scs-field-${name}`);
inputs.forEach(input=> {
if(input.type==='checkbox'||input.type==='radio'){
if(dynamicFieldsData[name].includes(input.value)) input.checked=true;
}else{
input.value=dynamicFieldsData[name];
}});
});
}
function loadChatHistory(){
scsUi.getElements().chatContainer.innerHTML='';
chatHistory.forEach(msg=> {
scsUi.addMessage(msg.sender, msg.text, {
isUser: msg.sender===scsUtils.__('you'),
isSecurityAlert: msg.sender==='Alerta'||msg.sender==='Error'||msg.sender===scsUtils.__('securityAlert'),
timestamp: msg.timestamp
});
});
}
function saveLocalStorage(){
if(typeof (Storage)==="undefined") return;
localStorage.setItem(LS_KEY_NAME, userName);
localStorage.setItem(LS_KEY_EMAIL, userEmail);
localStorage.setItem(LS_KEY_PHONE, userPhone);
localStorage.setItem(LS_KEY_DYNAMIC, JSON.stringify(dynamicFieldsData));
localStorage.setItem(LS_KEY_HISTORY, JSON.stringify(chatHistory));
localStorage.setItem(LS_KEY_CHAT_ID, chatSessionId);
localStorage.setItem(LS_KEY_EXPIRY, new Date().getTime().toString());
}
function clearLocalStorage(){
if(typeof (Storage)==="undefined") return;
[LS_KEY_NAME, LS_KEY_EMAIL, LS_KEY_PHONE, LS_KEY_DYNAMIC, LS_KEY_HISTORY, LS_KEY_CHAT_ID, LS_KEY_EXPIRY].forEach(key=> localStorage.removeItem(key));
}
function handleNewChatSubmit(e){
e.preventDefault();
const privacyCheckbox=document.getElementById('scs-privacy-policy');
if(privacyCheckbox&&!privacyCheckbox.checked){
alert(scsUtils.__('acceptPrivacy'));
return;
}
dynamicFieldsData={};
let validationError='';
document.querySelectorAll('.scs-dynamic-field-row').forEach(row=> {
const name=row.dataset.name;
const type=row.dataset.type;
const isRequired=row.dataset.required==='1';
const validation=row.dataset.validation||'none';
const label=row.querySelector('.form-label')?.textContent?.replace('*', '').trim()||name;
let value='';
if(type==='text'||type==='textarea'||type==='select'){
value=row.querySelector('.scs-dynamic-input')?.value.trim()||'';
}else if(type==='radio'){
value=row.querySelector('.scs-dynamic-input:checked')?.value||'';
}else if(type==='checkbox'){
value=Array.from(row.querySelectorAll('.scs-dynamic-input:checked')).map(el=> el.value).join(', ');
}
if(isRequired&&!value) validationError=scsUtils.__('fieldRequired', { label: label });
dynamicFieldsData[name]=value;
});
if(validationError){ alert(validationError); return; }
userName=dynamicFieldsData['nombre']||'';
userEmail=dynamicFieldsData['email']||'';
userPhone=dynamicFieldsData['telefono']||'';
chatHistory=[];
chatSessionId='chat-' + Math.random().toString(36).substring(2, 15) + '-' + Date.now();
saveLocalStorage();
scsUi.getElements().startFormContainer.style.setProperty('display', 'none', 'important');
scsUi.getElements().chatInterface.style.display='flex';
const greeting=scsConfig.greetingMessage
.replace(/{name}/g, userName)
.replace(/{agente}/g, scsConfig.botName);
const ts=new Date().toISOString();
scsUi.addMessage(scsUtils.__('assistant'), greeting, { timestamp: ts });
chatHistory.push({ sender: scsUtils.__('assistant'), text: greeting, timestamp: ts });
saveLocalStorage();
scsUi.playNotificationSound();
sendEarlyContext();
}
async function sendEarlyContext(){
console.log('Enviando registro temprano (Early Context)...');
try {
await scsApi.sendToProxy({
user_info: {
name: userName,
email: userEmail,
phone: userPhone,
chat_session_id: chatSessionId,
...dynamicFieldsData
},
conversation_history: "[SCS_EARLY_CONTEXT]",
event_type: 'USER_IDENTIFIED',
security_token: scsConfig.securityToken,
page_context: {
current_url: window.location.href,
page_title: scsConfig.postTitle||document.title,
post_type: scsConfig.postType||'unknown',
utm_params: utmParams,
referrer: referrer
}});
} catch (error){
console.error('Error al enviar registro temprano:', error);
}}
async function sendMessage(){
const input=scsUi.getElements().userInput;
if(!input) return;
const message=input.value.trim();
if(!message&&selectedFiles.length===0) return;
const ts=new Date().toISOString();
const displayMessage=message||(selectedFiles.length > 0 ? (selectedFiles.length===1 ? scsUtils.__('attachment'):scsUtils.__('attachments', { n: selectedFiles.length })):'');
scsUi.addMessage(scsUtils.__('you'), displayMessage, { isUser: true, timestamp: ts });
input.value='';
checkInputAndToggleSendButton();
const msgForHistory=displayMessage;
const sanitizedMsg=scsConfig.securityMode==='SANITIZE' ? scsUtils.sanitizeInput(msgForHistory):msgForHistory;
scsUi.toggleLoading(true);
let attachmentUrls=[];
if(selectedFiles.length > 0){
try {
for (const file of selectedFiles){
const formData=new FormData();
formData.append('file', file);
formData.append('email', userEmail);
console.log('[SCS DEBUG] Subiendo archivo:', file.name);
const uploadResponse=await fetch(scsConfig.uploadUrl, {
method: 'POST',
body: formData,
headers: {
'X-WP-Nonce': scsConfig.nonce
}});
const uploadData=await uploadResponse.json();
if(uploadData.success){
attachmentUrls.push(uploadData.url);
}else{
throw new Error(uploadData.message||`Error al subir ${file.name}`);
}}
selectedFiles=[];
scsUi.hideFilePreview();
} catch (uploadError){
scsUi.toggleLoading(false);
console.error('[SCS DEBUG] Error de upload:', uploadError);
scsUi.addMessage('Error', scsUtils.__('uploadingFailed') + uploadError.message, { isSecurityAlert: true });
return;
}}
const primaryAttachmentUrl=attachmentUrls.length > 0 ? attachmentUrls[0]:'';
const allAttachmentUrls=attachmentUrls.join(', ');
chatHistory.push({
sender: scsUtils.__('you'),
text: sanitizedMsg,
timestamp: ts,
attachment_url: primaryAttachmentUrl,
attachments: attachmentUrls
});
const controller=scsApi.createAbortController();
try {
const chatHistoryPlainText=chatHistory.map(msg=> {
let text=`${msg.sender}: ${msg.text}`;
if(msg.attachments&&msg.attachments.length > 0){
text +=` [Archivos: ${msg.attachments.join(', ')}]`;
}else if(msg.attachment_url){
text +=` [Archivo: ${msg.attachment_url}]`;
}
return text;
}).join('\n');
const data=await scsApi.sendToProxy({
user_info: { name: userName, email: userEmail, phone: userPhone, chat_session_id: chatSessionId, ...dynamicFieldsData },
conversation_history: chatHistoryPlainText,
last_message: sanitizedMsg,
attachment_url: allAttachmentUrls,
attachments: attachmentUrls,
security_token: scsConfig.securityToken,
page_context: {
current_url: window.location.href,
page_title: scsConfig.postTitle||document.title,
post_type: scsConfig.postType||'unknown',
utm_params: utmParams,
referrer: referrer
}}, controller.signal);
scsUi.toggleLoading(false);
if(data&&data.output){
const botTs=new Date().toISOString();
let outputText=data.output;
const isFinChat=outputText.includes('[FIN_CHAT]');
if(isFinChat) outputText=outputText.replace('[FIN_CHAT]', '').trim();
scsUi.addMessage(scsUtils.__('assistant'), outputText, { timestamp: botTs });
chatHistory.push({ sender: scsUtils.__('assistant'), text: outputText, timestamp: botTs });
saveLocalStorage();
scsUi.playNotificationSound();
if(isFinChat&&scsConfig.csatEnabled==='1'){
renderCsatSurvey();
}}
} catch (error){
scsUi.toggleLoading(false);
if(error.name!=='AbortError'){
scsUi.addMessage('Error', error.message, { isSecurityAlert: true });
}}
}
function renderCsatSurvey(){
const elements=scsUi.getElements();
if(elements.userInput){
elements.userInput.disabled=true;
elements.userInput.placeholder=scsUtils.__('chatFinished');
elements.userInput.classList.add('scs-input-locked');
}
if(elements.sendBtn) elements.sendBtn.disabled=true;
const container=document.createElement('div');
container.className='scs-csat-container';
const title=document.createElement('div');
title.className='scs-csat-title';
title.textContent=scsConfig.csatTitle;
container.appendChild(title);
const options=document.createElement('div');
options.className='scs-csat-options';
let icons=[];
if(scsConfig.csatType==='stars') icons=['⭐', '⭐', '⭐', '⭐', '⭐'];
else if(scsConfig.csatType==='thumbs') icons=['👍', '👎'];
else icons=['😍', '😐', '😞'];
icons.forEach((icon, index)=> {
const span=document.createElement('span');
span.className='scs-csat-option';
span.textContent=icon;
span.onclick=()=> handleCsatRating(index + 1, icon, container);
options.appendChild(span);
});
container.appendChild(options);
elements.chatContainer.appendChild(container);
scsUi.scrollToBottom();
}
async function handleCsatRating(rating, label, container){
container.innerHTML=`<div class="scs-csat-thanks">${scsConfig.csatThanks}</div>`;
scsUi.scrollToBottom();
try {
await scsApi.sendToProxy({
user_info: { name: userName, email: userEmail, phone: userPhone, ...dynamicFieldsData },
event_type: 'FEEDBACK_RATING',
rating: rating,
rating_label: label,
security_token: scsConfig.securityToken,
page_context: {
current_url: window.location.href,
page_title: scsConfig.postTitle||document.title
}});
} catch (error){
console.error('Error al enviar valoración:', error);
}}
if(document.readyState==='loading'){
document.addEventListener('DOMContentLoaded', init);
}else{
init();
}})();