/**
 * AI CHAT WIDGET - V25
 * Autor: Dejavu AI
 */
(function() {
    const ENABLE_DEBUG = false;
    const myScript = document.currentScript || document.querySelector('script[src*="widget-loader.js"]');
    
    // Logger System
    const log = (msg, data) => { if(ENABLE_DEBUG) console.log(`%c📘 AI INFO: ${msg}`, 'color:#2563eb;font-weight:bold', data || ''); };
    const logReq = (url, data) => { if(ENABLE_DEBUG) { console.groupCollapsed(`%c🚀 ENVIANDO: ${url}`, 'color:#8b5cf6'); console.log(data); console.groupEnd(); }};
    const logRes = (status, data) => { if(ENABLE_DEBUG) { console.groupCollapsed(`%c⬅️ RECIBIDO (${status})`, status<300?'color:#10b981':'color:#f59e0b'); console.log(data); console.groupEnd(); }};
    const err = (msg, e) => { console.error(`%c🚨 AI ERROR: ${msg}`, 'color:red;font-weight:bold', e || ''); };

    if (!myScript) { err("No se encontró la etiqueta script."); return; }

    const config = {
        id: myScript.getAttribute('data-id'),
        token: myScript.getAttribute('data-token'),
        
        primaryColor: myScript.getAttribute('data-color-header-y-boton') || '#0f172a',
        userBg: myScript.getAttribute('data-color-fondo-msj-usuario') || '#2563eb',
        userText: myScript.getAttribute('data-color-texto-msj-usuario') || '#ffffff',
        botBg: myScript.getAttribute('data-color-fondo-msj-bot') || '#f8fafc',
        botText: myScript.getAttribute('data-color-texto-msj-bot') || '#334155',
        msgAreaBg: myScript.getAttribute('data-color-fondo-area-mensajes') || '#ffffff',
        winBg: myScript.getAttribute('data-color-fondo-ventana') || '#ffffff',
        accent: myScript.getAttribute('data-color-enlaces') || '#2563eb',
        shadow: myScript.getAttribute('data-sombra-ventana') || '0 12px 40px rgba(0,0,0,0.12)',
        
        position: myScript.getAttribute('data-posicion-pantalla') || 'right',
        zIndex: myScript.getAttribute('data-z-index') || '999999',
        opacity: myScript.getAttribute('data-opacidad-ventana') || '1',

        botName: myScript.getAttribute('data-nombre-del-bot') || 'Asistente',
        botAvatar: myScript.getAttribute('data-imagen-avatar-url') || '',
        toggleIcon: myScript.getAttribute('data-imagen-boton-flotante-url') || '',
        
        welcomeMsg: myScript.getAttribute('data-mensaje-bienvenida') || 'Hola',
        placeholder: myScript.getAttribute('data-texto-input-escribir') || 'Escribe...',
        footerText: myScript.getAttribute('data-texto-pie-pagina') || 'Powered by AI',
        footerLink: myScript.getAttribute('data-link-pie-pagina') || '#',
        connError: myScript.getAttribute('data-mensaje-error-conexion') || 'Error de conexión',
        resetConfirm: myScript.getAttribute('data-mensaje-confirmar-borrado') || '¿Reiniciar chat?',
        
        autoOpen: parseInt(myScript.getAttribute('data-tiempo-auto-apertura')) || 0,
        
        apiUrlInit: "https://cdn.dejavuai.cloud/api/initWeb",
        apiUrlMsg: "https://cdn.dejavuai.cloud/api/entrada"
    };

    log("Configuración V19 cargada:", config);

    if (!config.id || !config.token) { err("Faltan credenciales (ID o Token)."); return; }

    const style = document.createElement('style');
    const posCss = config.position === 'left' ? 'left: 24px; right: auto;' : 'right: 24px; left: auto;';
    style.innerHTML = `
        :root { --aw-primary:${config.primaryColor}; --aw-user-bg:${config.userBg}; --aw-user-text:${config.userText}; --aw-bot-bg:${config.botBg}; --aw-bot-text:${config.botText}; --aw-msg-bg:${config.msgAreaBg}; --aw-win-bg:${config.winBg}; --aw-accent:${config.accent}; --aw-shadow:${config.shadow}; --aw-font:inherit; }
        .aw-wrapper * { box-sizing: border-box; } .hidden { display: none !important; }
        #ai-widget-bot { position: fixed; bottom: 24px; ${posCss} z-index: ${config.zIndex}; font-family: var(--aw-font); font-size: 14px; line-height: 1.5; }
        #aw-toggle-btn { width: 60px; height: 60px; border-radius: 50%; background: var(--aw-primary); color: white; border: none; cursor: pointer; box-shadow: 0 4px 15px rgba(0,0,0,0.2); display: flex; align-items: center; justify-content: center; transition: transform 0.2s; position: relative; overflow: hidden; }
        #aw-toggle-btn:hover { transform: scale(1.08); } #aw-toggle-btn img { width: 80%;  object-fit: contain; }
        .aw-badge { position: absolute; top: -2px; right: -2px; background: #ef4444; color: white; font-size: 11px; font-weight: 700; width: 22px; height: 22px; border-radius: 50%; display: flex; align-items: center; justify-content: center; border: 2px solid white; animation: aw-pop 0.3s; }
        @keyframes aw-pop { from { transform: scale(0); } to { transform: scale(1); } }
        #aw-window { position: absolute; bottom: 80px; ${config.position === 'left' ? 'left: 0;' : 'right: 0;'} width: 380px; height: 600px; max-height: 80vh; background: var(--aw-win-bg); border-radius: 16px; box-shadow: var(--aw-shadow); border: 1px solid rgba(0,0,0,0.1); display: flex; flex-direction: column; overflow: hidden; opacity: 0; transform: translateY(20px) scale(0.95); pointer-events: none; transition: all 0.3s ease; visibility: hidden; }
        #aw-window.visible { opacity: ${config.opacity} !important; transform: translateY(0) scale(1); pointer-events: auto; visibility: visible !important; }
        .aw-header { background: var(--aw-primary); color: white; padding: 16px; display: flex; justify-content: space-between; align-items: center; }
        .aw-title-group { display: flex; align-items: center; gap: 10px; }
        .aw-avatar { width: 40px; height: 40px; background: rgba(255,255,255,0.15); border-radius: 50%; display: flex; align-items: center; justify-content: center; overflow: hidden; }
        .aw-avatar img { width: 80%;  object-fit: cover; }
        .aw-name { font-weight: 600; font-size: 14px; } .aw-status { font-size: 11px; opacity: 0.8; display: flex; align-items: center; gap: 4px; } .aw-dot { width: 6px; height: 6px; background: #22c55e; border-radius: 50%; }
        .aw-actions { display: flex; gap: 4px; }
        .aw-icon-btn { background: transparent; border: none; color: white; width: 30px; height: 30px; border-radius: 6px; cursor: pointer; display: flex; align-items: center; justify-content: center; opacity: 0.85; } .aw-icon-btn:hover { background: rgba(255,255,255,0.2); opacity: 1; }
        .aw-messages { flex: 1; padding: 20px; overflow-y: auto; background: var(--aw-msg-bg); display: flex; flex-direction: column; gap: 14px; }
        .aw-msg { max-width: 85%; padding: 10px 14px; border-radius: 12px; word-wrap: break-word; font-size: 14px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); }
        .aw-msg.bot { align-self: flex-start; background: var(--aw-bot-bg); color: var(--aw-bot-text); border-top-left-radius: 2px; }
        .aw-msg.user { align-self: flex-end; background: var(--aw-user-bg); color: var(--aw-user-text); border-top-right-radius: 2px; }
        .aw-msg.error { align-self: center; background: #fee2e2; color: #b91c1c; font-size: 12px; padding: 6px 12px; border-radius: 20px; }
        .aw-msg p { margin: 0 0 6px 0; } .aw-msg a { color: var(--aw-accent); text-decoration: underline; } .aw-msg ul { padding-left: 20px; margin: 5px 0; }
        .aw-input-area { padding: 16px; border-top: 1px solid rgba(0,0,0,0.05); display: flex; gap: 10px; background: var(--aw-win-bg); }
        #aw-input { flex: 1; padding: 12px 16px; border: 1px solid rgba(0,0,0,0.1); border-radius: 24px; outline: none; font-size: 14px; background: rgba(0,0,0,0.02); color: inherit; }
        #aw-input:focus { border-color: var(--aw-primary); background: var(--aw-win-bg); }
        #aw-send-btn { width: 42px; height: 42px; border-radius: 50%; background: var(--aw-primary); color: white; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
        .aw-footer { text-align: center; font-size: 10px; padding: 6px; background: rgba(0,0,0,0.02); color: #94a3b8; } .aw-footer a { color: #94a3b8; text-decoration: none; }
        .aw-typing span { width: 5px; height: 5px; background: #94a3b8; border-radius: 50%; display: inline-block; margin: 0 1px; animation: aw-bounce 1.4s infinite ease-in-out both; }
        .aw-typing span:nth-child(1) { animation-delay: -0.32s; } .aw-typing span:nth-child(2) { animation-delay: -0.16s; }
        @keyframes aw-bounce { 0%, 80%, 100% { transform: scale(0); } 40% { transform: scale(1); } }
        @media (max-width: 480px) { #aw-window { width: calc(100vw - 32px); bottom: 90px; height: 75vh; } ${config.position === 'left' ? 'left: 16px;' : 'right: 16px;'} #ai-widget-bot { bottom: 16px; ${config.position === 'left' ? 'left: 16px;' : 'right: 16px;'} } }
    `;
    document.head.appendChild(style);

    //HTML
    const toggleIcon = config.toggleIcon ? `<img src="${config.toggleIcon}">` : `<svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>`;
    const avatarIcon = config.botAvatar ? `<img src="${config.botAvatar}">` : `<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2 2 2 0 0 1-2-2V4a2 2 0 0 1 2-2Z"/><path d="m8 6 4-4 4 4"/><path d="M12 18v4"/><path d="m8 18 4 4 4-4"/><rect x="3" y="10" width="18" height="8" rx="2"/></svg>`;

    const div = document.createElement('div');
    div.id = 'ai-widget-bot'; div.className = 'aw-wrapper';
    div.innerHTML = `<button id="aw-toggle-btn" aria-label="Abrir chat">${toggleIcon}<span id="aw-badge" class="aw-badge hidden">0</span></button><div id="aw-window"><div class="aw-header"><div class="aw-title-group"><div class="aw-avatar">${avatarIcon}</div><div class="aw-info"><span class="aw-name">${config.botName}</span><span class="aw-status"><span class="aw-dot"></span> En línea</span></div></div><div class="aw-actions"><button class="aw-icon-btn" id="aw-reset-btn"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"></path><path d="M21 3v5h-5"></path><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"></path><path d="M8 16H3v5"></path></svg></button><button class="aw-icon-btn" id="aw-close-btn"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg></button></div></div><div id="aw-messages" class="aw-messages"></div><div class="aw-input-area"><input type="text" id="aw-input" autocomplete="off" placeholder="${config.placeholder}"><button id="aw-send-btn"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg></button></div><div class="aw-footer"><a href="${config.footerLink}" target="_blank">${config.footerText}</a></div></div>`;
    document.body.appendChild(div);

    function randomId(len = 24) {
      const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
      let out = '';
      for (let i = 0; i < len; i++) out += chars[Math.floor(Math.random() * chars.length)];
      return out;
    }

    const incomingSession = localStorage.getItem(`aw_sess_${config.id}`);
    const finalSessionId = (typeof incomingSession === 'string' && incomingSession.trim().length >= 8)
      ? incomingSession.trim()
      : randomId(24);
    
    if(finalSessionId !== incomingSession) {
        localStorage.setItem(`aw_sess_${config.id}`, finalSessionId);
    }
     
    // STATE INIT
    let state = { isOpen: false, sess: finalSessionId, token: localStorage.getItem(`aw_token_${config.id}`), typing: false, unread: 0 };
    const ui = { win: document.getElementById('aw-window'), msgs: document.getElementById('aw-messages'), input: document.getElementById('aw-input'), badge: document.getElementById('aw-badge'), toggle: document.getElementById('aw-toggle-btn'), close: document.getElementById('aw-close-btn'), reset: document.getElementById('aw-reset-btn'), send: document.getElementById('aw-send-btn') };

    const toggle = () => { state.isOpen = !state.isOpen; ui.win.classList.toggle('visible', state.isOpen); if(state.isOpen){ state.unread=0; ui.badge.classList.add('hidden'); ui.badge.textContent=0; setTimeout(()=>ui.input.focus(),300); scroll(); } };
    const scroll = () => requestAnimationFrame(() => ui.msgs.scrollTop = ui.msgs.scrollHeight);
    
  const parse = (t) => {
    if (!t) return "";

    t = t
        .replace(/\\"/g, '"')   // \" -> "
        .replace(/\\n/g, '\n'); // \n literal -> salto de línea real

    const hasHtmlLink = /<a\s[^>]*href=/i.test(t);
    t = t.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>');
    t = t.replace(
        /\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,
        '<a href="$2" target="_blank" rel="noopener">$1</a>'
    );
    t = t.replace(/\n/g, '<br>');
    if (hasHtmlLink) {
        return t;
    }
    t = t.replace(/(^|\s)((https?:\/\/|www\.)[^\s<]+)/g, (match, space, url) => {
        let trailing = '';
        while (/[.,!?)]$/.test(url)) {
            trailing = url.slice(-1) + trailing;
            url = url.slice(0, -1);
        }
        const href = url.startsWith('www.') ? 'https://' + url : url;
        return `${space}<a href="${href}" target="_blank" rel="noopener">${url}</a>${trailing}`;
    });
    t = t.replace(
        /([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[A-Za-z]{2,})/g,
        '<a href="mailto:$1">$1</a>'
    );
        return t;
    };

    const addMsg = (txt, type, save=true) => { 
        const d = document.createElement('div'); 
        d.className = `aw-msg ${type}`; 
        if (type === 'bot') { 
            d.innerHTML = parse(txt); 
            if (!state.isOpen && save) { state.unread++; ui.badge.textContent=state.unread; ui.badge.classList.remove('hidden'); } 
        } else { d.textContent = txt; } 
        ui.msgs.appendChild(d); scroll(); 
        if(save) saveMsg({txt,type}); 
    };

    const saveMsg = (m) => { let h=JSON.parse(localStorage.getItem(`aw_hist_${config.id}`)||'[]'); h.push(m); if(h.length>50)h.shift(); localStorage.setItem(`aw_hist_${config.id}`,JSON.stringify(h)); };
    const api = async (ep, data) => { logReq(ep, data); const r = await fetch(ep, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)}); const j=await r.json(); logRes(r.status, j); return j; };
    const handshake = async () => { try { const d = await api(config.apiUrlInit, {widget_public_id:config.id,signed_token:config.token}); if(d.signed_token){ state.token=d.signed_token; localStorage.setItem(`aw_token_${config.id}`,state.token); } } catch(e){ err("Error Handshake", e); } };

    ui.toggle.onclick = (e) => { e.stopPropagation(); toggle(); };
    ui.close.onclick = (e) => { e.stopPropagation(); toggle(); };
    
    ui.reset.onclick = () => { 
        if(!confirm(config.resetConfirm))return; 
        localStorage.removeItem(`aw_hist_${config.id}`); 
        localStorage.removeItem(`aw_sess_${config.id}`); 
        localStorage.removeItem(`aw_token_${config.id}`); 
        
        state.sess = randomId(24); // Usa la nueva función
        localStorage.setItem(`aw_sess_${config.id}`, state.sess); 
        
        state.token=null; 
        ui.msgs.innerHTML=''; 
        handshake().then(()=>addMsg(config.welcomeMsg,'bot',false)); 
    };
    
    ui.send.onclick = async () => {
        const txt = ui.input.value.trim(); if(!txt)return;
        addMsg(txt, 'user'); ui.input.value=''; 
        if(!state.token) await handshake();

        try {
            const rawRes = await api(config.apiUrlMsg, {widget_public_id:config.id, signed_token:state.token, message:txt, session_id:state.sess});
            
            let res = Array.isArray(rawRes) ? rawRes[0] : rawRes;
            
            if(res.status === 401 || res.status === 403 || (res.status === 'error' && res.error_code === 'TOKEN_EXPIRED')) {
                log("⚠️ Token expirado detectado. Renovando...");
                await handshake(); 
                const rawRes2 = await api(config.apiUrlMsg, {widget_public_id:config.id, signed_token:state.token, message:txt, session_id:state.sess});
                res = Array.isArray(rawRes2) ? rawRes2[0] : rawRes2;
            }

            if(res.reply) addMsg(res.reply, 'bot');
            else if (res.status === 'error') addMsg("⚠️ " + (res.reply || "Error desconocido"), 'error', false);

        } catch(e) { 
            err("Error fatal en envío", e);
            addMsg(config.connError, 'error', false); 
        }
    };

    ui.input.onkeypress = (e) => { if(e.key==='Enter') ui.send.click(); };
    document.addEventListener('click', (e) => { if(state.isOpen && !ui.win.contains(e.target) && !ui.toggle.contains(e.target)) toggle(); });

    // Carga de historial
    const hist = JSON.parse(localStorage.getItem(`aw_hist_${config.id}`)||'[]');
    if(hist.length) {
        hist.forEach(m => {
            const safeText = m.txt || m.text || ""; 
            addMsg(safeText, m.type, false);
        });
    } else {
        addMsg(config.welcomeMsg,'bot',false);
    }

    setTimeout(() => { if(config.autoOpen > 0 && !state.isOpen) toggle(); }, config.autoOpen);
})();
