(function(){
'use strict';

var SAB_REST=(window.SabrielAI&&window.SabrielAI.restUrl)||'/wp-json/sabriel/v1';
function sabUrl(percorso,query){
  var u=SAB_REST+(percorso||'');
  if(query){ u+=(u.indexOf('?')>-1?'&':'?')+query; }
  return u;
}

var NOTIFY=(window.SabrielAI&&window.SabrielAI.notifyEmail)||'';
var BUSINESS_NAME=(window.SabrielAI&&window.SabrielAI.businessName)||'';
var PHONE_DISPLAY=(window.SabrielAI&&window.SabrielAI.phoneDisplay)||'';

var BOT_NAME_LIVE=(window.SabrielAI&&window.SabrielAI.botName)||(window.SabrielAI&&window.SabrielAI.businessName)||'';
var LOGO_URL_LIVE=(window.SabrielAI&&window.SabrielAI.logoUrl)||'';

var SAB_STAT_ON=!(window.SabrielAI&&('statistiche' in window.SabrielAI)&&!Number(window.SabrielAI.statistiche));
function sabTracciaTraffico(datiExtra){
  if(!SAB_STAT_ON) return;
  try{
    var oggi=new Date().toISOString().slice(0,10);
    var base=getSabFingerprint()+'|'+oggi;
    var h=0;
    for(var i=0;i<base.length;i++){h=((h<<5)-h)+base.charCodeAt(i);h|=0;}
    var visitanteOggi=Math.abs(h).toString(36);
    var payload={v:visitanteOggi};
    for(var k in datiExtra){payload[k]=datiExtra[k];}
    fetch(sabUrl('/traffico/log'),{
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body: JSON.stringify(payload)
    }).catch(function(){});
  }catch(e){}
}
sabTracciaTraffico({percorso:location.pathname});
var sabChatApertaTracciata=false;

var SAB_LOCALE=(window.SabrielAI&&window.SabrielAI.localeJs)||'it-IT';
var SAB_I18N=(window.SabrielAI&&window.SabrielAI.i18n)||{};
function sabT(chiave){
  var s=SAB_I18N[chiave];
  if(typeof s!=='string') return chiave;
  var args=Array.prototype.slice.call(arguments,1);
  s=s.replace(/%(\d+)\$[sd]/g,function(m,n){var v=args[parseInt(n,10)-1];return v===undefined?m:String(v);});
  s=s.replace(/%%/g,'\u0000PCT\u0000');
  var i=0;
  s=s.replace(/%[sd]/g,function(m){var v=args[i++];return v===undefined?m:String(v);});
  return s.replace(/\u0000PCT\u0000/g,'%');
}
var _sabKwCache={};
function sabParoleChiave(chiave){
  if(_sabKwCache[chiave]) return _sabKwCache[chiave];
  var grezzo=(typeof SAB_I18N[chiave]==='string'&&SAB_I18N[chiave].trim())?SAB_I18N[chiave]:'';
  var re;
  try{ re=grezzo?new RegExp(grezzo,'i'):/$a/; }
  catch(e){ re=/$a/; }
  _sabKwCache[chiave]=re;
  return re;
}

var MAX_IMG=(window.SabrielAI&&parseInt(window.SabrielAI.maxAllegatoByte,10))||10*1024*1024;

var LEGGE_PDF=!(window.SabrielAI&&('leggePdf' in window.SabrielAI)&&!window.SabrielAI.leggePdf);
var SAB_TEMP_EMAIL_DOMAINS=(window.SabrielAI&&window.SabrielAI.emailTemporanee)||[];
function sabEmailTemporanea(email){
  var pos=email.lastIndexOf('@');
  if(pos===-1)return false;
  var dominio=email.substring(pos+1).toLowerCase().trim();
  return SAB_TEMP_EMAIL_DOMAINS.indexOf(dominio)>-1;
}

var WA_NUM=(window.SabrielAI&&window.SabrielAI.whatsappNumber)||'';
var KS='sa_sess_v3',KU='sa_user_v3';
try{ window.sabTranscriptToken=localStorage.getItem('sab_trtok_v1')||''; }catch(e){ window.sabTranscriptToken=''; }

function lg(k){try{return JSON.parse(localStorage.getItem(k))}catch(e){return null}}
function ls(k,v){try{localStorage.setItem(k,JSON.stringify(v));return true;}catch(e){return false;}}
function getSess(){return lg(KS)||[]}

function sabSenzaAllegati(sessioni){
  return sessioni.map(function(s){
    if(!s||!Array.isArray(s.hist))return s;
    var copia={};
    for(var k in s){if(Object.prototype.hasOwnProperty.call(s,k))copia[k]=s[k];}
    copia.hist=s.hist.map(function(t){
      if(!t||!Array.isArray(t.parts))return t;
      var soloTesto=t.parts.filter(function(p){return p&&typeof p.text!=='undefined';});
      if(soloTesto.length===t.parts.length)return t;
      if(!soloTesto.length)soloTesto=[{text:'[image sent earlier in this conversation]'}];
      return {role:t.role,parts:soloTesto};
    });
    return copia;
  });
}
var MAX_CONVERSAZIONI=30;
function setSess(a){
  var lista=sabSenzaAllegati(a.slice(0,MAX_CONVERSAZIONI));
  if(ls(KS,lista))return true;
  /* ⚠ Memoria del browser piena: si buttano le conversazioni PIU' VECCHIE una
     alla volta e si riprova. Quella in corso e' la prima e non si perde mai.
     Prima non si salvava niente in silenzio e la chat aperta risultava mozzata. */
  while(lista.length>1){
    lista=lista.slice(0,lista.length-1);
    if(ls(KS,lista))return true;
  }
  return false;
}
function getUser(){return lg(KU)}
function setUser(u){ls(KU,u)}

var isOpen=false,sc='',user=null,sess=null,imgQ=null,busy=false,emaild=0,viewHist=false,scrollY=0,liveShown=false,liveResume=null,liveResumePromise=null,inactTimer=null,INACT_MS=5*60*1000,attInfoShown=false;

function q(id){return document.getElementById(id)}
var root=q('sar'),win=q('sar-win'),tog=q('sar-tog'),ndot=q('sar-ndot');

(function applyBubbleIcon(){
  var scelta=(window.SabrielAI&&window.SabrielAI.bubbleIcon)||'chat';
  if(scelta==='chat') return;
  var icEl=tog&&tog.querySelector('.ic');
  if(!icEl) return;
  var svgAlt={
    message:'<svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z"/><polyline points="22 6 12 13 2 6"/></svg>',
    spark:'<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l2.2 7.8L22 12l-7.8 2.2L12 22l-2.2-7.8L2 12l7.8-2.2z"/></svg>',
    dots:'<svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><circle cx="6" cy="12" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="18" cy="12" r="2"/></svg>',
    robot:'<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="8" width="16" height="12" rx="2"/><circle cx="9" cy="14" r="1" fill="currentColor"/><circle cx="15" cy="14" r="1" fill="currentColor"/><path d="M12 8V4"/><circle cx="12" cy="3" r="1.2" fill="currentColor"/></svg>',
    headset:'<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M4 13v-1a8 8 0 0 1 16 0v1"/><rect x="2.5" y="13" width="4" height="6" rx="1.5"/><rect x="17.5" y="13" width="4" height="6" rx="1.5"/></svg>',
    bell:'<svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>',
    smile:'<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/></svg>'
  };
  if(svgAlt[scelta]) icEl.innerHTML=svgAlt[scelta];
})();
if(root&&document.body&&root.parentNode!==document.body){document.body.appendChild(root);}
var hbhist=q('sar-hbhist'),hbback=q('sar-hbback');
var scw=q('sar-sc-w'),scc=q('sar-sc-c'),sch=q('sar-sc-h');
var msgs=q('sar-msgs'),robanner=q('sar-robanner'),rotext=q('sar-rotext'),roback=q('sar-roback');
var ia=q('sar-ia'),ap=q('sar-ap'),aprm=q('sar-aprm'),att=q('sar-att'),fi=q('sar-fi'),mic=q('sar-mic');
var ta=q('sar-ta'),snd=q('sar-snd'),hl=q('sar-hl'),toast=q('sar-toast');

function isMobile(){return window.innerWidth<=640||window.innerHeight<=500}

var toastT;
function showToast(msg){toast.textContent=msg;toast.classList.add('show');clearTimeout(toastT);toastT=setTimeout(function(){toast.classList.remove('show')},3200);}

var SAR_HDR='#header-wrapper,.fusion-header-wrapper,.fusion-header,.fusion-tb-header,#masthead,.site-header,#wpadminbar';
var sabBodyBloccato=false;
function lockBody(){
  if(!isMobile())return;
  sabBodyBloccato=true;
  scrollY=window.scrollY||window.pageYOffset;
  document.body.style.position='fixed';document.body.style.top='-'+scrollY+'px';
  document.body.style.width='100%';document.body.style.overflow='hidden';
  document.querySelectorAll(SAR_HDR).forEach(function(el){if(el.dataset.sarOldVis===undefined){el.dataset.sarOldVis=el.style.visibility;}el.style.setProperty('visibility','hidden','important');});
}
function unlockBody(){

  if(!sabBodyBloccato)return;
  sabBodyBloccato=false;
  document.body.style.position='';document.body.style.top='';
  document.body.style.width='';document.body.style.overflow='';
  window.scrollTo(0,scrollY);
  document.querySelectorAll(SAR_HDR).forEach(function(el){el.style.visibility=el.dataset.sarOldVis||'';delete el.dataset.sarOldVis;});
}

function applyVVP(){
  if(!isOpen)return;
  if(!isMobile()){ win.style.height=''; win.style.top=''; return; }
  var vvp=window.visualViewport;
  if(vvp){win.style.height=Math.round(vvp.height)+'px';win.style.top=Math.round(vvp.offsetTop)+'px';setTimeout(function(){msgs.scrollTop=msgs.scrollHeight;},50);}
  else{win.style.height=window.innerHeight+'px';win.style.top='0px';}
}
if(window.visualViewport){window.visualViewport.addEventListener('resize',applyVVP);window.visualViewport.addEventListener('scroll',applyVVP);}

function show(name){
  sc=name;[scw,scc,sch].forEach(function(e){e.classList.remove('on')});
  ({welcome:scw,chat:scc,history:sch})[name].classList.add('on');
  hbhist.style.display=(name==='chat'&&!viewHist)?'flex':'none';
  hbback.style.display=(name==='history'||viewHist)?'flex':'none';
}

function openChat(){
  if(!sabChatApertaTracciata){sabChatApertaTracciata=true;sabTracciaTraffico({tipo:'chat'});}
  isOpen=true;win.classList.add('open');tog.classList.add('open');
  tog.setAttribute('aria-expanded','true');ndot.style.opacity='0';
  lockBody();
  if(isMobile()){tog.classList.add('mob-gone');setTimeout(applyVVP,50);}
  user=getUser();
  if(!user){show('welcome');}
  else{
    if(!sess){resumeOrStartSess();}
    show('chat');
    var blk=checkLocalBlock();
    if(blk){
      showRateLimit(blk.tomorrow);
      try{
        var _fpChk=getSabFingerprint();
        var _emChk=user?user.email:'';
        fetch(sabUrl('/chat/status','fp='+encodeURIComponent(_fpChk)+'&em='+encodeURIComponent(_emChk)))
          .then(function(r){return r.json();})
          .then(function(d){
            if(d&&d.ok&&!d.blocked){
              try{localStorage.removeItem(getSabBlockKey());}catch(e){}
              var ovChk=document.getElementById('sar-rate-overlay');
              if(ovChk)ovChk.style.display='none';
            }
          }).catch(function(){});
      }catch(e){}
    }
    setTimeout(function(){ta.focus()},350);
  }
}

function ripristinaBolla(){
  tog.classList.remove('mob-gone');
  win.style.height='';win.style.top='';
}
function closeChat(){
  stopInactTimer();
  isOpen=false;win.classList.remove('open');tog.classList.remove('open');
  tog.setAttribute('aria-expanded','false');
  ripristinaBolla();
  unlockBody();
}

tog.addEventListener('click',function(){if(isOpen){closeChat();sendEmail();}else{openChat();}});

q('sar-hbclose').addEventListener('click',showConfirm);
q('sar-hbmin').addEventListener('click',minimizeChat);
q('sar-cyes').addEventListener('click',function(){hideConfirm();closeChat();sendEmail();try{localStorage.removeItem('sa_last_act');}catch(e){}sess=null;});
q('sar-cno').addEventListener('click',hideConfirm);
q('sar-hbprofile').addEventListener('click',function(){
  if(!user){showToast(sabT('compilaModulo'));return;}
  q('sar-pnome').value=user.name||'';
  q('sar-pcognome').value=user.surname||'';
  q('sar-pemail').value=user.email||'';
  q('sar-ptel').value=user.tel||'';
  q('sar-profov').classList.add('on');
  var ov=document.getElementById('sar-rate-overlay');if(ov)ov.style.display='none';
});
q('sar-pcancel').addEventListener('click',function(){
  q('sar-profov').classList.remove('on');
  var ov=document.getElementById('sar-rate-overlay');if(ov)ov.style.display='';
});
q('sar-psave').addEventListener('click',function(){
  var nome=q('sar-pnome').value.trim();
  var cognome=q('sar-pcognome').value.trim();
  var email=q('sar-pemail').value.trim();
  if(!nome){showToast(sabT('nomeVuoto'));return;}
  if(!cognome){showToast(sabT('cognomeVuoto'));return;}
  if(!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)){showToast(sabT('emailNonValida'));return;}
  var btnSave=this;btnSave.disabled=true;
  if(sabEmailTemporanea(email)){showToast(sabT('emailTemporanea'));btnSave.disabled=false;return;}

  user={name:nome,surname:cognome,email:email,tel:q('sar-ptel').value.trim()};
  setUser(user);
  btnSave.disabled=false;
  q('sar-profov').classList.remove('on');
  var ov2=document.getElementById('sar-rate-overlay');if(ov2)ov2.style.display='';
  showToast(sabT('datiAggiornati'));
});
q('sar-profov').addEventListener('click',function(e){
  if(e.target===this){
    this.classList.remove('on');
    var ov=document.getElementById('sar-rate-overlay');if(ov)ov.style.display='';
  }
});
document.addEventListener('keydown',function(e){if(e.key==='Escape'&&isOpen){closeChat();sendEmail();}});
var mdInsideWidget=false;
document.addEventListener('mousedown',function(e){mdInsideWidget=root.contains(e.target);});
document.addEventListener('click',function(e){
  var haSelezioneTesto=(window.getSelection && window.getSelection().toString().length>0);
  if(isOpen&&!isMobile()&&!root.contains(e.target)&&e.target!==toast&&document.body.contains(e.target)&&!haSelezioneTesto&&!mdInsideWidget){closeChat();sendEmail();}
});

q('sar-sbtn').addEventListener('click',function(){
  var name=q('sar-fname').value.trim(),surn=q('sar-fsurn').value.trim(),email=q('sar-femail').value.trim();
  var errN=q('sar-ferr-name'),errS=q('sar-ferr-surn'),errE=q('sar-ferr-email'),ok=true;
  errN.classList.remove('on');errS.classList.remove('on');errE.classList.remove('on');
  q('sar-fname').classList.remove('err');q('sar-fsurn').classList.remove('err');q('sar-femail').classList.remove('err');
  if(!name){errN.classList.add('on');q('sar-fname').classList.add('err');q('sar-fname').focus();ok=false;}
  if(!surn){errS.classList.add('on');q('sar-fsurn').classList.add('err');if(ok)q('sar-fsurn').focus();ok=false;}
  if(!email||!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)){errE.classList.add('on');q('sar-femail').classList.add('err');if(ok)q('sar-femail').focus();ok=false;}
  if(!ok)return;
  var btnIniziale=this;btnIniziale.disabled=true;
  var temp=sabEmailTemporanea(email);
  btnIniziale.disabled=false;
  if(temp){q('sar-femail').classList.add('err');q('sar-femail').focus();showToast(sabT('emailTemporanea'));return;}
  user={name:name,surname:surn,email:email,tel:(q('sar-ftel')?q('sar-ftel').value.trim():'')};
  setUser(user);startSess();show('chat');setTimeout(function(){ta.focus()},350);
});
['sar-fname','sar-fsurn','sar-femail','sar-ftel'].forEach(function(id){
  var elEnter=q(id);
  if(elEnter)elEnter.addEventListener('keydown',function(e){
    if(e.key==='Enter'){e.preventDefault();q('sar-sbtn').click();}
  });
});
['sar-fname','sar-fsurn','sar-femail'].forEach(function(id){
  q(id).addEventListener('input',function(){q(id).classList.remove('err');if(id==='sar-fname')q('sar-ferr-name').classList.remove('on');if(id==='sar-fsurn')q('sar-ferr-surn').classList.remove('on');if(id==='sar-femail')q('sar-ferr-email').classList.remove('on');});
});

function msgsToHist(msgsArr){
  return msgsArr.map(function(m){
    return {role:(m.from==='user'?'user':'model'), parts:[{text:m.text||(m.img?sabT('imgAllegata'):'')}]};
  });
}
function resumeOrStartSess(){
  var all=getSess();
  var ultima=all[0];
  var lastAct=null; try{ lastAct=localStorage.getItem('sa_last_act'); }catch(e){}
  var ancoraFresca=lastAct && (Date.now()-parseInt(lastAct)) < 5*60*1000;
  if(ultima && ultima.user && user && ultima.user.email===user.email && ultima.msgs && ultima.msgs.length>0 && ancoraFresca){
    sess={id:ultima.id,ts:ultima.ts,msgs:ultima.msgs.slice(),hist:msgsToHist(ultima.msgs)};
    clearMsgs();
    sess.msgs.forEach(function(m){
      var row=mkRow(m.from==='user'?'user':'bot');
      var d=document.createElement('div');d.className='sar-b '+(m.from==='user'?'user':'bot');
      d.innerHTML=m.from==='user'?esc(m.text||(m.img?sabT('imgAllegata'):'')):parseMsg(m.text||(m.img?sabT('imgAllegata'):''));
      if(m.from==='user'){row.appendChild(d);row.appendChild(mkAvUser());}else{row.appendChild(mkAvBot());row.appendChild(d);}
      msgs.appendChild(row);
    });
    scroll();
  } else {
    startSess();
  }
}
function startSess(){
  sess={id:Date.now().toString(),ts:Date.now(),msgs:[],hist:[]};
  emaild=0;liveShown=false;liveResume=null;attInfoShown=false;clearMsgs();
  setTimeout(function(){addBot(sabT('benvenuto',user.name,BUSINESS_NAME))},300);
}
function sabCostruisciMemoria(email){
  if(!email) return '';
  try{
    var all=getSess();
    if(!all||!all.length) return '';
    var prec=all.filter(function(s){
      return s && s.user && s.user.email===email && (!sess || s.id!==sess.id) && s.msgs && s.msgs.length;
    });
    if(!prec.length) return '';
    prec.sort(function(a,b){return (b.ts||0)-(a.ts||0);});
    prec=prec.slice(0,3);
    var righe=prec.map(function(s){
      var when='';
      try{ when=s.ts?new Date(s.ts).toLocaleDateString(SAB_LOCALE):''; }catch(e){}
      var testi=s.msgs.filter(function(m){return m && m.from==='user' && m.text;}).map(function(m){return String(m.text);});
      var estratto=testi.join(' | ');
      if(estratto.length>280) estratto=estratto.slice(0,280);
      return (when?('('+when+') '):'')+estratto;
    }).filter(function(x){return x;});
    var out=righe.join(String.fromCharCode(10));
    if(out.length>900) out=out.slice(0,900);
    return out;
  }catch(e){ return ''; }
}
function saveSess(){
  if(!sess||sess.msgs.length===0)return;
  if(!sess.msgs.some(function(m){return m.from==='user';}))return;
  var all=getSess(),i=all.findIndex(function(s){return s.id===sess.id});
  var d={id:sess.id,ts:sess.ts,user:Object.assign({},user),msgs:sess.msgs.slice()};
  if(i>=0)all[i]=d;else all.unshift(d);
  if(!setSess(all)&&!_avvisoMemoriaDato){_avvisoMemoriaDato=true;showToast(sabT('cronNonSalvata'));}
}
var _avvisoMemoriaDato=false;

function clearMsgs(){while(msgs.lastChild&&msgs.lastChild!==robanner)msgs.removeChild(msgs.lastChild);msgs.insertBefore(robanner,msgs.firstChild);robanner.classList.remove('on');}
function addBot(text){
  removeTyping();
  var row=mkRow('bot');row.appendChild(mkAvBot());
  var d=document.createElement('div');d.className='sar-b bot';d.innerHTML=parseMsg(text);
  row.appendChild(d);msgs.appendChild(row);scroll();
  if(sess){sess.hist.push({role:'model',parts:[{text:text}]});sess.msgs.push({from:'bot',text:text});saveSess();}
  resetInactTimer();
}
function addUser(text,att){
  var row=mkRow('user');
  var d=document.createElement('div');d.className='sar-b user';
  if(text)d.textContent=text;
  if(att&&att.isPdf){
    var chip=document.createElement('div');
    chip.style.cssText='display:flex;align-items:center;gap:7px;margin-top:'+(text?'8px':'0')+';background:rgba(127,127,127,0.18);border-radius:9px;padding:6px 10px';
    chip.innerHTML='<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>'
      +'<span style="font-size:11.5px;color:inherit;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:180px">'+sabEsc(att.name)+'</span>';
    d.appendChild(chip);
  }else if(att&&att.url){
    var img=document.createElement('img');img.src=att.url;img.alt=sabT('imgAllegata');d.appendChild(img);
  }
  row.appendChild(d);row.appendChild(mkAvUser());msgs.appendChild(row);scroll();
}
function showTyping(){var row=mkRow('bot');row.id='sar-typ-row';row.appendChild(mkAvBot());var d=document.createElement('div');d.className='sar-typ';d.innerHTML='<span></span><span></span><span></span>';row.appendChild(d);msgs.appendChild(row);scroll();}

function removeTyping(){var e=q('sar-typ-row');if(e)e.remove();}
function scroll(){setTimeout(function(){msgs.scrollTop=msgs.scrollHeight},50);}

function sabAlleggerisciStoria(st){
  var ultimo=st.length-1,fuori=[];
  st.forEach(function(t,i){
    if(!t||!t.parts||!t.parts.length){return;}
    if(i===ultimo){fuori.push(t);return;}
    var testo=t.parts.filter(function(p){return p&&typeof p.text!=='undefined';});
    var avevaImg=testo.length!==t.parts.length;
    if(!testo.length&&avevaImg){testo=[{text:'[image sent earlier in this conversation]'}];}
    if(testo.length){fuori.push({role:t.role,parts:testo});}
  });
  return fuori;
}

async function doSend(){
  var txt=ta.value.trim();
  if((!txt&&!imgQ)||busy)return;
  var img=imgQ;imgQ=null;clearAP();
  addUser(txt,img);
  resetInactTimer();
  var parts=[];
  if(txt)parts.push({text:txt});
  if(img)parts.push({inlineData:{mimeType:img.mime,data:img.b64}});
  if(sess){sess.hist.push({role:'user',parts:parts});sess.msgs.push({from:'user',text:txt||'',img:!!img});saveSess();}
  ta.value='';ta.style.height='auto';
  busy=true;snd.disabled=true;showTyping();
  var sabAbortCtrl=new AbortController();
  var sabTimeoutId=setTimeout(function(){sabAbortCtrl.abort();},25000);
  try{
    var _fp=getSabFingerprint();
    var _em=user?user.email:'';
    var r=await fetch(sabUrl('/chat'),{
      method:'POST',headers:{'Content-Type':'application/json','X-Sab-Fp':_fp,'X-Sab-User':_em},
      signal:sabAbortCtrl.signal,
      body:JSON.stringify({
        contents:sess?sabAlleggerisciStoria(sess.hist.slice(-60)):parts,
        modo:'chat',
        memoria:sabCostruisciMemoria(_em)
      })
    });
    clearTimeout(sabTimeoutId);
    var data=await r.json();
    if(data&&data.rate_limited){
      removeTyping();
      setLocalBlock(data.retry_after||86400, data.tomorrow||null);
      window.showRateLimit(data.tomorrow||null);
      busy=false;updSnd();
      return;
    }
    if(data&&data.ai_overload){
      removeTyping();
      if(sess){sess.hist.pop();saveSess();}
      addBot(sabT('servizioOccupato'));
      if(sess){sess.hist.pop();saveSess();}
      busy=false;updSnd();
      return;
    }
    if(data&&data.error){
      if(sess){sess.hist.pop();saveSess();}
      addBot(sabT('servizioErrore',NOTIFY));
      if(sess){sess.hist.pop();saveSess();}
      busy=false;updSnd();
      return;
    }
    var rep=data&&data.candidates&&data.candidates[0]&&data.candidates[0].content&&data.candidates[0].content.parts&&data.candidates[0].content.parts[0]?data.candidates[0].content.parts[0].text:'';
    if(data&&data.sab_transcript_token){ window.sabTranscriptToken=data.sab_transcript_token; try{localStorage.setItem('sab_trtok_v1',data.sab_transcript_token);}catch(e){} }
    rep=(rep||'').trim()||sabT('nonHoCapito',NOTIFY);
    rep=rep.replace(/\u2014/g,',').replace(/\u2013/g,'-');
    rep=rep.replace(/^\s*[.\-\u2013\u2014]{1,3}\s*\n+/,'').trim();
    var hasLive=rep.indexOf('[LIVE]')>-1;

    if(hasLive){
      var userAsksLive=sabParoleChiave('kwLive').test(txt);
      if(!liveShown||userAsksLive){
        liveShown=true;liveResumePromise=generateLiveResume();
      }else{
        rep=rep.replace(/\[LIVE\]/g,'').trim();
        hasLive=false;
      }
    }

    rep=sabPulisciMarcatoriSpenti(rep,{live:hasLive,booking:false,autobook:false,preventivo:false,portfolio:false,audit:false});

    addBot(rep);
  }catch(e){
    clearTimeout(sabTimeoutId);
    if(sess){sess.hist.pop();saveSess();}
    addBot(sabT('prevConnessioneKo',NOTIFY,PHONE_DISPLAY));
    if(sess){sess.hist.pop();saveSess();}
  }
  busy=false;updSnd();

  try{ localStorage.setItem('sa_last_act',Date.now()); }catch(e){}
}
snd.addEventListener('click',doSend);
ta.addEventListener('keydown',function(e){
  if(e.isComposing||e.keyCode===229) return;
  if(e.key==='Enter'&&!e.shiftKey){
    if(busy) return;
    e.preventDefault();
    doSend();
  }
});
ta.addEventListener('focus',function(){setTimeout(applyVVP,300);});
ta.addEventListener('input',function(){ta.style.height='auto';ta.style.height=Math.min(ta.scrollHeight,90)+'px';updSnd();});
function updSnd(){snd.disabled=(ta.value.trim()===''&&!imgQ)||busy;}

(function(){
  var SR=window.SpeechRecognition||window.webkitSpeechRecognition;
  if(!SR||!mic) return;
  mic.style.display='flex';
  var rec=new SR();
  rec.lang=SAB_LOCALE;
  rec.interimResults=true;
  rec.maxAlternatives=1;
  rec.continuous=true;
  var ascolto=false, baseValue='', micTimeoutMax=null, micTimeoutSilenzio=null;
  mic.addEventListener('click',function(){
    if(ascolto){ rec.stop(); return; }
    try{
      baseValue = ta.value.trim() ? ta.value.trim()+' ' : '';
      rec.start();
    }catch(e){}
  });
  function armaTimeoutSilenzio(){
    if(micTimeoutSilenzio) clearTimeout(micTimeoutSilenzio);
    micTimeoutSilenzio=setTimeout(function(){ if(ascolto) rec.stop(); },3200);
  }
  rec.onstart=function(){
    ascolto=true; mic.classList.add('sar-mic-on');
    micTimeoutMax=setTimeout(function(){ if(ascolto) rec.stop(); },60000);
    armaTimeoutSilenzio();
  };
  rec.onresult=function(ev){
    var testo='';
    for(var i=0;i<ev.results.length;i++) testo+=ev.results[i][0].transcript;
    ta.value = baseValue + testo;
    ta.dispatchEvent(new Event('input'));
    armaTimeoutSilenzio();
  };
  rec.onerror=function(ev){
    if(ev.error==='not-allowed'||ev.error==='service-not-allowed') showToast(sabT('micNegato'));
    else if(ev.error!=='no-speech'&&ev.error!=='aborted') showToast(sabT('micNonSentito'));
  };
  rec.onend=function(){
    ascolto=false; mic.classList.remove('sar-mic-on'); ta.focus();
    if(micTimeoutMax){clearTimeout(micTimeoutMax);micTimeoutMax=null;}
    if(micTimeoutSilenzio){clearTimeout(micTimeoutSilenzio);micTimeoutSilenzio=null;}
  };
})();

att.addEventListener('click',function(){

  if(!attInfoShown){
    attInfoShown=true;
    showToast(sabT('allegatoLimite',Math.floor(MAX_IMG/1048576)+'MB'));
  }
  fi.click();
});
fi.addEventListener('change',function(e){
  var f=e.target.files[0];if(!f)return;
  if(f.size>MAX_IMG){showToast(sabT('allegatoTroppoGr',Math.floor(MAX_IMG/1048576)+'MB'));e.target.value='';return;}
  var isPdf=f.type==='application/pdf';

  if(isPdf&&!LEGGE_PDF){showToast(sabT('allegatoNientePdf'));e.target.value='';return;}
  if(!isPdf&&!f.type.match(/^image\/(jpeg|png|webp|gif)$/)){showToast(sabT('allegatoFormato'));e.target.value='';return;}
  var rd=new FileReader();
  rd.onload=function(ev){
    var url=ev.target.result;
    if(isPdf){
      imgQ={b64:url.split(',')[1],mime:f.type,url:url,name:f.name,isPdf:isPdf};
      ap.innerHTML='';
      var chip=document.createElement('div');
      chip.style.cssText='display:flex;align-items:center;gap:7px;background:#fff;border:1.5px solid #e5e5e5;border-radius:9px;padding:6px 10px;max-width:100%';
      chip.innerHTML='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#d92b2b" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>'
        +'<span style="font-size:11.5px;color:#555;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">'+sabEsc(f.name)+'</span>';
      ap.appendChild(chip);
      ap.appendChild(aprm);ap.classList.add('on');updSnd();
    }else{
      var testImg=new Image();
      testImg.onload=function(){
        imgQ={b64:url.split(',')[1],mime:f.type,url:url,name:f.name,isPdf:isPdf};
        ap.innerHTML='';
        var img=document.createElement('img');img.src=url;img.alt=sabT('allegatoAnteprima');
        ap.appendChild(img);
        ap.appendChild(aprm);ap.classList.add('on');updSnd();
      };
      testImg.onerror=function(){
        showToast(sabT('allegatoRotto'));
      };
      testImg.src=url;
    }
  };
  rd.readAsDataURL(f);e.target.value='';
});
aprm.addEventListener('click',clearAP);
function clearAP(){imgQ=null;ap.innerHTML='';ap.appendChild(aprm);ap.classList.remove('on');updSnd();}

hbhist.addEventListener('click',function(){renderHist();show('history');});
hbback.addEventListener('click',function(){if(viewHist)exitViewHist();else show('chat');});
roback.addEventListener('click',exitViewHist);
function renderHist(){
  var all=getSess();hl.innerHTML='';
  var nuova=document.createElement('div');nuova.id='sar-newchat';
  nuova.innerHTML='<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg><span>'+sabT('cronNuovaConv')+'</span>';
  nuova.addEventListener('click',function(){saveSess();sendEmail();startSess();show('chat');});
  hl.appendChild(nuova);

  if(all.length===0){
    var vuoto=document.createElement('div');vuoto.id='sar-he';vuoto.textContent=sabT('cronVuota');
    hl.appendChild(vuoto);return;
  }
  all.forEach(function(s){
    var d=document.createElement('div');d.className='sar-hi';
    var dt=new Date(s.ts).toLocaleDateString(SAB_LOCALE,{day:'2-digit',month:'2-digit',year:'numeric'});
    var tm=new Date(s.ts).toLocaleTimeString(SAB_LOCALE,{hour:'2-digit',minute:'2-digit'});
    var full=(s.user?((s.user.name||'')+' '+(s.user.surname||'')).trim():sabT('utenteAnonimo'));
    var prv=s.msgs.find(function(m){return m.from==='user';});
    prv=prv?(prv.text||sabT('imgBreve')):'';
    d.innerHTML='<div class="sar-hii"><div class="sar-hin">'+esc(full)+'</div><div class="sar-hid">'+dt+' \u00B7 '+tm+' \u00B7 '+s.msgs.length+' msg</div><div class="sar-hip">'+esc(prv)+'</div></div><button class="sar-hdel" title="'+sabEscAttr(sabT('cronElimina'))+'">\u2715</button>';
    d.querySelector('.sar-hdel').addEventListener('click',function(ev){ev.stopPropagation();setSess(getSess().filter(function(x){return x.id!==s.id;}));renderHist();});
    d.addEventListener('click',function(){viewSession(s);});
    hl.appendChild(d);
  });
}
function viewSession(s){
  viewHist=true;clearMsgs();
  var dt=new Date(s.ts).toLocaleDateString(SAB_LOCALE,{day:'2-digit',month:'2-digit',year:'numeric'});
  rotext.textContent=sabT('cronSessioneDel',dt);
  robanner.classList.add('on');ia.style.display='none';
  var ov=document.getElementById('sar-rate-overlay');if(ov)ov.style.display='none';
  s.msgs.forEach(function(m){
    var row=mkRow(m.from==='user'?'user':'bot');
    var d=document.createElement('div');d.className='sar-b '+(m.from==='user'?'user':'bot');
    d.innerHTML=m.from==='user'?esc(m.text||(m.img?sabT('imgAllegata'):'')):parseMsg(m.text||(m.img?sabT('imgAllegata'):''));
    if(m.from==='user'){row.appendChild(d);row.appendChild(mkAvUser());}else{row.appendChild(mkAvBot());row.appendChild(d);}
    msgs.appendChild(row);
  });
  show('chat');scroll();
}
function exitViewHist(){
  viewHist=false;ia.style.display='';robanner.classList.remove('on');clearMsgs();
  var ov=document.getElementById('sar-rate-overlay');if(ov)ov.style.display='';
  if(sess){sess.msgs.forEach(function(m){
    var row=mkRow(m.from==='user'?'user':'bot');
    var d=document.createElement('div');d.className='sar-b '+(m.from==='user'?'user':'bot');
    d.innerHTML=m.from==='user'?esc(m.text||(m.img?sabT('imgAllegata'):'')):parseMsg(m.text||(m.img?sabT('imgAllegata'):''));
    if(m.from==='user'){row.appendChild(d);row.appendChild(mkAvUser());}else{row.appendChild(mkAvBot());row.appendChild(d);}
    msgs.appendChild(row);
  });scroll();}
  show('chat');
}
q('sar-hclear').addEventListener('click',function(){if(confirm(sabT('cronEliminaTutto'))){setSess([]);renderHist();}});

async function sendEmail(){
  if(!sess||!user)return;
  var msgsSnapshot=sess.msgs.slice();
  var tsSnapshot=sess.ts;
  var um=msgsSnapshot.filter(function(m){return m.from==='user';});
  if(um.length===0)return;

  if(um.length<=emaild)return;
  var _emaildPrima=emaild;
  emaild=um.length;
  var nome=((user.name+' '+(user.surname||'')).trim());
  var data=new Date(tsSnapshot).toLocaleString(SAB_LOCALE);

  var userMsgs=msgsSnapshot.map(function(m){
    return{from:m.from==='user'?nome:BUSINESS_NAME,text:m.text||(m.img?sabT('imgAllegata'):''),isUser:m.from==='user'};
  });

  /* ⚠ La risposta va guardata: un 403 o un 429 passavano per invii riusciti e
     `emaild` restava alzato, quindi nemmeno l'uscita dalla pagina riprovava. */
  try{
    var _r=await fetch(sabUrl('/transcript'),{
      method:'POST',headers:{'Content-Type':'application/json'},
      body:JSON.stringify({name:nome,email:user.email,date:data,messages:userMsgs,token:(window.sabTranscriptToken||'')})
    });
    if(!_r||!_r.ok)emaild=_emaildPrima;
  }catch(e){emaild=_emaildPrima;console.warn('[Sabriel] transcript:',e);}
}

async function generateLiveResume(){
  if(!sess||sess.msgs.length<2){liveResume=null;return;}
  try{
    var nome=user?((user.name+' '+(user.surname||'')).trim()):sabT('utenteAnonimo');
    var tuttiMsgs=sess.msgs.map(function(m){return(m.from==='user'?nome:'Bot')+': '+(m.text||sabT('imgBreve'));}).join('\n');

    var sabEtRisposta=sabT('waBriefingEtichettaRisposta');
    var prompt=sabT('waBriefingPrompt',BUSINESS_NAME,nome,sabEtRisposta,tuttiMsgs);
    var _fp=getSabFingerprint();
    var _em=user?user.email:'';
    var r=await fetch(sabUrl('/chat'),{
      method:'POST',headers:{'Content-Type':'application/json','X-Sab-Fp':_fp,'X-Sab-User':_em},
      body:JSON.stringify({contents:[{role:'user',parts:[{text:prompt}]}],modo:'briefing'})
    });
    var d=await r.json();
    var raw=d&&d.candidates&&d.candidates[0]&&d.candidates[0].content&&d.candidates[0].content.parts&&d.candidates[0].content.parts[0]?d.candidates[0].content.parts[0].text:'';
    liveResume=raw.trim()||null;
    document.querySelectorAll('.sar-lbtn-wa').forEach(function(a){
      a.href=buildWaLink();
    });
  }catch(e){liveResume=null;}
}

function buildWaLink(){
  var info=user?((user.name+' '+(user.surname||'')).trim())+' - '+user.email+(user.tel?' - '+user.tel:''):sabT('utenteAnonimo');
  var body='';
  if(liveResume){

    var sabEt=sabT('waBriefingEtichettaRisposta').replace(/[.*+?^${}()|[\]\\]/g,'\\$&');
    var resumeClean=liveResume.replace(new RegExp(sabEt+'[^\n]*','gi'),'').replace(/\n{3,}/g,'\n\n').trim();
    body='\n\n'+resumeClean;
  }else if(sess&&sess.msgs.length>0){
    var um=sess.msgs.filter(function(m){return m.from==='user';}).slice(-3);
    body='\n\n'+sabT('waUltimiMsg')+'\n'+um.map(function(m){return '- '+(m.text||sabT('imgBreve'));}).join('\n');
  }
  var txt='\uD83D\uDD14 '+sabT('waChatDa')+' '+info+body+sabT('rispondiQui');
  return 'https://wa.me/'+WA_NUM.replace(/[^0-9]/g,'')+'?text='+encodeURIComponent(txt.substring(0,950));
}
document.addEventListener('click', function(e){
  var waBtn = e.target.closest && e.target.closest('.sar-lbtn-wa');
  if(!waBtn) return;
  if(liveResume !== null) return;
  e.preventDefault();
  var done = false;
  var finish = function(){
    if(done) return; done = true;
    window.open(buildWaLink(), '_blank', 'noopener');
  };
  if(liveResumePromise) liveResumePromise.then(finish).catch(finish);
  setTimeout(finish, 4000);
});

document.addEventListener('click',function(e){
  var b=e.target.closest&&e.target.closest('.sar-msg-send');
  if(!b)return;
  e.preventDefault();
  sarSendMsg(b);
});
function buildMailLink(){
  var sub=sabT('emailOggetto',BUSINESS_NAME)+(user?' - '+user.name:'');
  var body=sabT('emailCorpo')+(user?sabT('emailNome',(user.name+' '+(user.surname||'')).trim())+'\n'+sabT('emailEmail',user.email)+'\n':'');
  if(sess&&sess.msgs.length>0){body+='\n'+sabT('mailChatSep')+'\n'+sess.msgs.map(function(m){return(m.from==='user'?(user?user.name:sabT('utenteAnonimo')):BOT_NAME_LIVE)+': '+(m.text||sabT('imgBreve'));}).join('\n');}
  return 'mailto:'+NOTIFY+'?subject='+encodeURIComponent(sub)+'&body='+encodeURIComponent(body.substring(0,1800));
}
function buildLiveHTML(){
  var waIcon='<svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>';
  return '<p class="sar-live-txt">'+sabT('liveContattaci')+'</p>'
    +(WA_NUM?'<a href="'+sabEscAttr(buildWaLink())+'" target="_blank" rel="noopener" class="sar-lbtn sar-lbtn-wa">'+waIcon+' '+sabT('liveWhatsapp')+'</a>':'')
    +(NOTIFY?'<a href="'+sabEscAttr(buildMailLink())+'" class="sar-lbtn sar-lbtn-em">'+sabT('scriviViaEmail')+'</a>':'')
    +(PHONE_DISPLAY?'<a href="tel:'+sabEscAttr(PHONE_DISPLAY.replace(/[^0-9+]/g,''))+'" class="sar-lbtn sar-lbtn-em">\uD83D\uDCDE '+sabEsc(PHONE_DISPLAY)+'</a>':'')
    +'<div class="sar-msg-box">'
    +'<textarea class="sar-msg-ta" placeholder="'+sabEscAttr(sabT('oppureScrivi'))+'"></textarea>'
    +'<button type="button" class="sar-msg-send">'+sabT('invioMessaggio')+'</button>'
    +'</div>';
}

async function sarSendMsg(btn){
  var box=btn.closest('.sar-msg-box');
  if(!box)return;
  var msgTa=box.querySelector('.sar-msg-ta');
  if(!msgTa||!msgTa.value.trim()){showToast(sabT('scriviPrima'));return;}
  var testo=msgTa.value.trim();
  btn.disabled=true;btn.textContent=sabT('invioInCorso');
  var nome=user?((user.name+' '+(user.surname||'')).trim()):sabT('utenteAnonimo');
  var emailU=user?user.email:'—';
  var telU=user&&user.tel?user.tel:'—';
  try{
    var risposta=await fetch(sabUrl('/quick-message'),{
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body:JSON.stringify({nome:nome,email:emailU,telefono:telU,messaggio:testo})
    });
    var risultato=await risposta.json();
    if(!risultato.ok) throw new Error(risultato.error||sabT('invioKo'));
    box.innerHTML='<div style="text-align:center;padding:12px;background:#f0fdf4;border-radius:10px;'
      +'font-size:13px;color:#15803d;font-weight:600">'
      +''+sabT('invioOk')+'</div>';
  }catch(e){
    btn.disabled=false;btn.textContent=sabT('invioMessaggio');
    showToast(sabT('invioErrore'));
  }
}

(function(){
  if(!LOGO_URL_LIVE) return;
  var avEl=document.getElementById('sar-av');
  if(avEl){ avEl.style.backgroundImage='none'; avEl.innerHTML='<img src="'+sabEscAttr(LOGO_URL_LIVE)+'" alt="" style="width:100%;height:100%;object-fit:contain">'; }
  var wlogoEl=document.querySelector('.sar-wlogo');
  if(wlogoEl){ wlogoEl.style.backgroundImage='none'; wlogoEl.innerHTML='<img src="'+sabEscAttr(LOGO_URL_LIVE)+'" alt="" style="width:100%;height:100%;object-fit:contain;border-radius:9px">'; }
})();

function showRateLimit(tomorrow){
  var taEl=document.getElementById('sar-ta');
  var sndEl=document.getElementById('sar-snd');
  if(taEl){taEl.disabled=true;taEl.placeholder=sabT('limiteGiornaliero');}
  if(sndEl) sndEl.disabled=true;

  var existing=document.getElementById('sar-rate-overlay');
  if(existing){existing.style.display='';return;}

  var container=document.getElementById('sar-sc-c');
  if(!container)container=document.getElementById('sar-win');
  container.style.position='relative';
  container.style.overflow='hidden';

  var whenText=tomorrow?sabT('limiteDal',tomorrow):sabT('limiteDomani');

  var overlay=document.createElement('div');
  overlay.className='sar-rate-overlay';
  overlay.id='sar-rate-overlay';
  overlay.innerHTML=
    '<div class="sar-rate-icon">\uD83D\uDD12</div>'
    +'<div class="sar-rate-tag">'+sabEsc(BOT_NAME_LIVE)+' &middot; '+sabT('statoOnline')+'</div>'
    +'<div class="sar-rate-title">'+sabT('limiteTitolo')+'</div>'
    +'<div class="sar-rate-sub">'+sabT('limiteRaggiunto')+'</div>'
    +'<div class="sar-rate-when">\uD83D\uDCC5\u00a0'+whenText+'</div>'
    +'<div class="sar-rate-divider"></div>'
    +'<div class="sar-rate-cta-label">'+sabT('limiteContattaci')+'</div>'
    +'<div class="sar-rate-btns">'
    +(WA_NUM?'<a class="sar-rate-btn wa" href="https://wa.me/'+sabEscAttr(WA_NUM.replace(/[^0-9]/g,''))+'" target="_blank" rel="noopener">WhatsApp</a>':'')
    +(NOTIFY?'<a class="sar-rate-btn em" href="mailto:'+sabEscAttr(NOTIFY)+'">'+sabT('limiteEmail')+'</a>':'')
    +'</div>';
  container.appendChild(overlay);
}
function getSabFingerprint(){
  var d=[
    navigator.userAgent,
    navigator.language||'',
    (screen.width||0)+'x'+(screen.height||0),
    screen.colorDepth||0,
    new Date().getTimezoneOffset(),
    navigator.hardwareConcurrency||0,
    navigator.platform||'',
    navigator.cookieEnabled?'1':'0',
    (navigator.plugins||[]).length
  ].join('|');
  var h=0;
  for(var i=0;i<d.length;i++){h=((h<<5)-h)+d.charCodeAt(i);h|=0;}
  return Math.abs(h).toString(36);
}
function getSabBlockKey(){return 'sab_blk_v1';}
function checkLocalBlock(){
  try{
    var b=JSON.parse(localStorage.getItem(getSabBlockKey())||'null');
    if(b&&b.until&&b.until>Date.now()) return b;
  }catch(e){}
  return null;
}
function setLocalBlock(retryAfterSec,tomorrow){
  try{
    localStorage.setItem(getSabBlockKey(),JSON.stringify({
      until:Date.now()+retryAfterSec*1000,
      tomorrow:tomorrow||null
    }));
  }catch(e){}
}
function minimizeChat(){
  stopInactTimer();
  isOpen=false;win.classList.remove('open');tog.classList.remove('open');
  tog.setAttribute('aria-expanded','false');
  ripristinaBolla();
  unlockBody();
  if(sess&&sess.msgs.filter(function(m){return m.from==='user';}).length>0){ndot.style.opacity='1';}
}
function showConfirm(){q('sar-confirm').classList.add('on');}
function hideConfirm(){q('sar-confirm').classList.remove('on');}

function mkAvBot(){
  var av=document.createElement('div');av.className='sar-av-sm bot';
  if(LOGO_URL_LIVE){
    var img=document.createElement('img');img.src=LOGO_URL_LIVE;img.alt='';
    img.style.width='100%';img.style.height='100%';img.style.objectFit='contain';
    img.onerror=function(){av.innerHTML='<span style="font-size:10px;font-weight:800;color:var(--sab-name-color)">'+sabEsc(BOT_NAME_LIVE.charAt(0).toUpperCase())+'</span>';};
    av.appendChild(img);
  } else {
    av.innerHTML='<span style="font-size:10px;font-weight:800;color:var(--sab-name-color)">'+sabEsc(BOT_NAME_LIVE.charAt(0).toUpperCase())+'</span>';
  }
  return av;
}
function mkAvUser(){var av=document.createElement('div');av.className='sar-av-sm user';av.textContent=(user&&user.name)?user.name.charAt(0).toUpperCase():'U';return av;}
function mkRow(cls){var r=document.createElement('div');r.className='sar-msg-row '+cls;return r;}
function esc(s){return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');}

function sabPulisciMarcatoriSpenti(testo,attivi){

  if(!attivi.live)       testo=testo.replace(/\[LIVE\]/gi,'');
  if(!attivi.booking)    testo=testo.replace(/\[BOOKING\]/gi,'');
  if(!attivi.autobook)   testo=testo.replace(/\[AUTOBOOK(?::[^\]]*)?\]/gi,'');
  if(!attivi.preventivo) testo=testo.replace(/\[PREVENTIVO(?::[^\]]*)?\]/gi,'');
  if(!attivi.portfolio)  testo=testo.replace(/\[PORTFOLIO[^\]]*\]/gi,'');
  if(!attivi.audit)      testo=testo.replace(/\[SITEAUDIT(?::[^\]]*)?\]/gi,'');
  return testo.trim();
}

function parseMsg(text){
  var s=text.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  /*
   * ⚠ OGNI LINK APPENA COSTRUITO SI METTE DA PARTE E SI RIMETTE PIU' AVANTI.
   * I riconoscitori qui sotto (email nuda, telefono nudo, indirizzo nudo) si
   * difendevano dal ricadere dentro un link gia' fatto guardando solo gli 8-12
   * caratteri PRECEDENTI. Con un testo del link un po' lungo quella finestra non
   * ci arriva e nasceva un <a> DENTRO un altro <a>: il browser non lo regge,
   * spezza il link in due tronconi e nella nuvoletta compare la doppia freccia.
   * Mettendoli da parte il problema sparisce alla radice.
   */
  var sabLinkFatti=[];
  function sabDaParte(html){ sabLinkFatti.push(html); return '\u0001'+(sabLinkFatti.length-1)+'\u0001'; }
  /* ⚠ PRIMA di quella sotto: l'etichetta VUOTA o fatta di soli spazi si tratta
     come un link nudo, non si lascia cadere. Senza questa riga in chat compariva
     «Il (https://... ↗) che ti ho preparato», parentesi comprese. */
  s=s.replace(/\[\s*\]\((https?:\/\/[^)"']+)\)/g,function(m,url){
    return sabDaParte('<a href="'+url+'" target="_blank" rel="noopener" class="sar-lk">'+url+' \u2197</a>');
  });
  s=s.replace(/\[([^\]]+)\]\((https?:\/\/[^)"']+)\)/g,function(m,testo,url){
    return sabDaParte('<a href="'+url+'" target="_blank" rel="noopener" class="sar-lk">'+testo+' ↗</a>');
  });
  s=s.replace(/\[([^\]]+)\]\((mailto:[^)"']+)\)/g,function(m,testo,url){
    return sabDaParte('<a href="'+url+'" class="sar-lk">'+testo+'</a>');
  });
  s=s.replace(/([a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,})/g,function(m,_,o,str){var b=str.substring(Math.max(0,o-12),o);if(b.indexOf('mailto:')>-1||b.indexOf('"')>-1)return m;return sabDaParte('<a href="mailto:'+m+'" class="sar-lk">\uD83D\uDCE7 '+m+'</a>');});
  s=s.replace(/(\+\d[\d\s]{6,16}\d)/g,function(m,_,o,str){var b=str.substring(Math.max(0,o-8),o);if(b.indexOf('tel:')>-1||b.indexOf('"')>-1)return m;return sabDaParte('<a href="tel:'+m.replace(/\s/g,'')+'" class="sar-lk">\uD83D\uDCDE '+m.trim()+'</a>');});
  s=s.replace(/(https?:\/\/[^\s<>"'\n)]+)/g,function(m,_,o,str){var b=str.substring(Math.max(0,o-8),o);if(b.indexOf('"')>-1)return m;return sabDaParte('<a href="'+m+'" target="_blank" rel="noopener" class="sar-lk">'+m+' ↗</a>');});
  /* ⚠ I link si rimettono QUI, PRIMA del grassetto: mettendoli dopo si perdeva
     il grassetto scritto DENTRO il testo di un link. */
  s=s.replace(/\u0001(\d+)\u0001/g,function(m,i){return sabLinkFatti[Number(i)]||'';});
  s=s.replace(/\*\*([^*\n]+)\*\*/g,'<strong>$1</strong>');
  if(s.indexOf('[LIVE]')>-1){s=s.replace(/\[LIVE\]\s*\.?/g,'<div class="sar-live-wrap">'+buildLiveHTML()+'</div>');}
  var lines=s.split('\n'),out=[],inL=false;
  lines.forEach(function(ln){
    var tr=ln.replace(/^[\s\u00A0]+/,'');
    if(/^[-•]\s/.test(tr)){if(!inL){out.push('<ul class="sar-ul">');inL=true;}out.push('<li>'+tr.replace(/^[-•]\s/,'')+'</li>');}
    else{if(inL){out.push('</ul>');inL=false;}if(tr===''){out.push('<div class="sar-gap"></div>');}else{out.push('<p>'+ln+'</p>');}}
  });
  if(inL)out.push('</ul>');
  return out.join('');
}

function resetInactTimer(){
  clearTimeout(inactTimer);
  if(!isOpen||!sess||sess.msgs.filter(function(m){return m.from==='user';}).length===0)return;
  inactTimer=setTimeout(function(){
    if(!isOpen||!sess)return;
    addBot(sabT('chatInattiva'));
    setTimeout(function(){
      if(isOpen){
        isOpen=false;win.classList.remove('open');tog.classList.remove('open');
        tog.setAttribute('aria-expanded','false');
        ripristinaBolla();
        unlockBody();
      }
      if(sess&&sess.msgs.filter(function(m){return m.from==='user';}).length>0){ndot.style.opacity='1';}
    },3500);
  },INACT_MS);
}
function stopInactTimer(){clearTimeout(inactTimer);inactTimer=null;}

function sabEsc(s){var d=document.createElement('div');d.textContent=String(s==null?'':s);return d.innerHTML;}
function sabEscAttr(s){return sabEsc(s).replace(/"/g,'&quot;').replace(/'/g,'&#39;');}

window.sarSendMsg=sarSendMsg;
window.showRateLimit=showRateLimit;

/* ⚠⚠ DUE GANCI, NON UNO. NON togliere `visibilitychange`: sul telefono il
   sistema CONGELA la pagina invece di chiuderla (cambio applicazione, schermo
   spento, indietro), quindi `pagehide` non parte mai e la trascrizione finale
   non arrivava. I doppioni li impedisce `emaild`. */
function sabRiepilogoDiUscita(){
  if(!sess||!user||!sess.msgs)return;
  var _umBeacon=sess.msgs.filter(function(m){return m.from==='user';}).length;
  if(_umBeacon===0||_umBeacon<=emaild)return;
  var _emaildPrima=emaild;
  emaild=_umBeacon;
  var nome=user.name+' '+(user.surname||'');
  var beaconMsgs=sess.msgs.map(function(m){
    return{from:m.from==='user'?nome:BUSINESS_NAME,text:m.text||(m.img?sabT('imgAllegata'):''),isUser:m.from==='user'};
  });

  var dataOra=new Date().toLocaleString(SAB_LOCALE);
  function sabPacchettoBeacon(msgs){
    return JSON.stringify({
      name:nome,
      email:user.email,
      date:dataOra,
      messages:msgs,
      token:(window.sabTranscriptToken||'')
    });
  }
  var data=sabPacchettoBeacon(beaconMsgs);
  var TETTO_BEACON=60000;
  while(beaconMsgs.length>4 && new Blob([data]).size>TETTO_BEACON){
    beaconMsgs=beaconMsgs.slice(1);
    data=sabPacchettoBeacon(beaconMsgs);
  }
  /* ⚠ L'esito di sendBeacon va letto: se rifiuta lo dice solo con un `false` e
     la trascrizione spariva in silenzio. Ripiego con `fetch` + `keepalive`. */
  var _inviato=false;
  try{_inviato=!!navigator.sendBeacon(sabUrl('/transcript'),new Blob([data],{type:'application/json'}));}catch(e){_inviato=false;}
  if(!_inviato){
    try{
      fetch(sabUrl('/transcript'),{method:'POST',headers:{'Content-Type':'application/json'},body:data,keepalive:true}).catch(function(){});
    }catch(e){emaild=_emaildPrima;}
  }
}
document.addEventListener('visibilitychange',function(){if(document.visibilityState==='hidden')sabRiepilogoDiUscita();});
window.addEventListener('pagehide',sabRiepilogoDiUscita);

show('welcome');user=getUser();
})();
