'
+''
+'';
var ss=k.querySelectorAll('.fbk-s');
function boya(v){ss.forEach(function(b){b.classList.toggle('on',+b.dataset.v<=v)});k.querySelector('.fbk-h').textContent=IP[v];}
ss.forEach(function(b){b.onclick=function(ev){ev.stopPropagation();puan=+b.dataset.v;boya(puan)};b.onmouseenter=function(){boya(+b.dataset.v)}});
k.querySelector('.fbk-stars').onmouseleave=function(){boya(puan)};
k.querySelector('.fbk-go').onclick=function(ev){
ev.stopPropagation();
var ta=k.querySelector('.fbk-ta'),er=k.querySelector('.fbk-err'),go=this,msg=(ta.value||'').trim();
if(msg.length<3){er.textContent='Please write a few words.';er.hidden=false;return;}
er.hidden=true;go.disabled=true;go.textContent='Sending…';
fetch('/r/'+encodeURIComponent(rv.uid),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({rating:puan,message:msg,uid:rv.uid})})
.then(function(r){return r.json().then(function(j){return {r:r,j:j}})}).then(function(x){
if(!x.r.ok||!x.j.ok)throw new Error((x.j&&x.j.message)||'Something went wrong.');
k.innerHTML='
✓ Thank you! Your feedback is live '+'★★★★★'.slice(0,puan)+''
+(x.j.reward&&x.j.reward.code?' Thank-you code: '+esc(x.j.reward.code)+'':'')+'
';
}).catch(function(e){er.textContent=e.message;er.hidden=false;go.disabled=false;go.textContent='Send feedback';});
};
k.onclick=function(ev){ev.stopPropagation();};
msgEl.appendChild(k); try{scrollDown();}catch(e){}
}).catch(function(){});
}
function attHtml(atts){
if(!atts||!atts.length)return '';
var h='';
atts.forEach(function(a){
if(a.type==='image'){h+='';}
else{h+='📄 '+esc(a.name||'file')+'';}
});
return h;
}
var TR_ON=false;
var TR_LANG=(navigator.language||'en').slice(0,2);
function toggleTr(){
TR_ON=!TR_ON;
var b=document.getElementById('trToggle');
if(b){b.style.borderColor=TR_ON?'var(--wa-acc)':'rgba(255,255,255,.2)';b.style.color=TR_ON?'var(--wa-acc)':'var(--wa-mut)';}
// açınca mevcut gelen mesajları çevir
if(TR_ON)document.querySelectorAll('.m.in[data-body]').forEach(function(d){trMsg(d)});
}
function trMsg(d){
if(d.querySelector('.tr-line'))return;
var txt=d.getAttribute('data-body')||'';if(!txt)return;
var tag=document.createElement('div');tag.className='tr-line';tag.textContent='…';d.insertBefore(tag,d.querySelector('time'));
fetch('/api/v1/livechat/translate',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({text:txt,target:TR_LANG})}).then(function(r){return r.json()}).then(function(j){tag.textContent='🌐 '+(j.text||'');}).catch(function(){tag.remove();});
}
var LC_EMOJI=['\u{1F44D}','\u2764\uFE0F','\u{1F602}','\u{1F62E}','\u{1F622}','\u{1F64F}'];
function lcTepkiCiz(harita){
if(!harita) return;
document.querySelectorAll('#msgs .m[data-mid]').forEach(function(d){
var kap=d.querySelector('.rx'); if(!kap) return;
var liste=harita[d.getAttribute('data-mid')]||[];
if(!liste.length){ kap.innerHTML=''; return; }
kap.innerHTML=liste.map(function(t){
return '';
}).join('');
kap.querySelectorAll('.rx-p').forEach(function(b){
b.onclick=function(ev){ev.stopPropagation();lcTepkiGonder(d.getAttribute('data-mid'),b.getAttribute('data-e'));};
});
});
}
function lcTepkiGonder(mid,emoji){
fetch('/api/v1/livechat/react',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({chatId:st.chatId,token:st.token,messageId:mid,emoji:emoji})})
.then(function(r){return r.json()})
.then(function(j){ if(j&&j.ok) lcTepkiCiz(j.reactions); })
.catch(function(){});
}
var lcSecici=null;
function lcEmojiAc(mid,dugme){
lcEmojiKapat();
var p=document.createElement('div');p.className='rx-pick';
p.innerHTML=LC_EMOJI.map(function(e){return '';}).join('');
document.body.appendChild(p);
var r=dugme.getBoundingClientRect();
var g=p.getBoundingClientRect().width||210;
p.style.left=Math.max(6,Math.min(r.left,window.innerWidth-g-6))+'px';
p.style.top=Math.max(6,r.top-46)+'px';
p.querySelectorAll('button').forEach(function(b){
b.onclick=function(ev){ev.stopPropagation();lcTepkiGonder(mid,b.getAttribute('data-e'));lcEmojiKapat();};
});
lcSecici=p;
setTimeout(function(){document.addEventListener('click',lcEmojiKapat,{once:true});},0);
}
function lcEmojiKapat(){ if(lcSecici){lcSecici.remove();lcSecici=null;} }
function add(m){
var msgs=document.getElementById('msgs');
var day=lcDayKey(m.created_at);
if(day && day!==st.lastDate){
var sep=document.createElement('div');sep.className='daysep';sep.innerHTML=''+esc(dayLabel(m.created_at))+'';
msgs.appendChild(sep);st.lastDate=day;
}
var d=document.createElement('div');d.className='m '+(m.sender==='customer'?'out':'in');
if(m.sender!=='customer' && m.body)d.setAttribute('data-body',m.body);
var inner='';
if(m.reply&&m.reply.id){
inner+=''+esc(m.reply.sender==='customer'?'You':'Support')+''
+''+esc(m.reply.body||'')+'';
}
inner+=m.body?linkify(esc(m.body)):'';
inner+=attHtml(m.attachments);
var tick=(m.sender==='customer')?'\u2713':'';
d.innerHTML=inner+'';
d.setAttribute('data-mid',m.id);
var qt=d.querySelector('.qt');
if(qt)qt.onclick=function(ev){ev.stopPropagation();lcAlintiyaGit(qt.getAttribute('data-to'));};
var rp=document.createElement('button');rp.className='rp-btn';rp.type='button';
rp.title='Reply';rp.textContent='\u21a9';
rp.onclick=function(ev){ev.stopPropagation();lcReplyAc(m);};
d.appendChild(rp);
var rw=document.createElement('div');rw.className='rx';d.appendChild(rw);
var rb=document.createElement('button');rb.className='rx-btn';rb.type='button';
rb.title='React';rb.textContent='\u263A';
rb.onclick=function(ev){ev.stopPropagation();lcEmojiAc(m.id,rb);};
d.appendChild(rb);
if(m.sender==='customer'){
d.setAttribute('data-id',m.id);
var u=document.createElement('span');u.className='unsend';u.textContent='\u21a9 unsend';
u.onclick=function(){lcUnsend(m.id,d);};
d.appendChild(u);
}
msgs.appendChild(d);
if(TR_ON && m.sender!=='customer' && m.body)trMsg(d);
if(m.sender!=='customer' && m.body){ var fbm=String(m.body).match(/\/r\/([^\s<>"'?#]+)/); if(fbm) lcFbKart(fbm[1], d); }
}
function uploadFiles(files){
if(!files||!files.length||!st.chatId)return;
var fd=new FormData();fd.append('chatId',st.chatId);fd.append('token',st.token);
if(st.replyTo){fd.append('reply_to',st.replyTo);lcReplyKapat();}
for(var i=0;i90?'\u2026':'');
document.getElementById('replyBar').classList.add('on');
var b=document.getElementById('box'); if(b)b.focus();
}
function lcReplyKapat(){ st.replyTo=null; document.getElementById('replyBar').classList.remove('on'); }
function lcAlintiyaGit(id){
var el=document.querySelector('#msgs .m[data-mid="'+id+'"]');
if(!el)return;
el.scrollIntoView({block:'center',behavior:'smooth'});
el.classList.remove('flash'); void el.offsetWidth; el.classList.add('flash');
}
function scrollDown(){var el=document.getElementById('msgs');el.scrollTop=el.scrollHeight}
function lcMode(m){
document.getElementById('formGuest').style.display=m==='guest'?'':'none';
document.getElementById('formCust').style.display=m==='cust'?'':'none';
var sp=document.getElementById('formSetpw'); if(sp)sp.style.display=m==='setpw'?'':'none';
if(m!=='setpw'){ document.getElementById('modeGuest').classList.toggle('on',m==='guest'); document.getElementById('modeCust').classList.toggle('on',m==='cust'); }
// Customer sekmesine her girişte adım 1'e (e-posta) dön.
if(m==='cust'){ var s1=document.getElementById('custStep1'),s2=document.getElementById('custStep2'); if(s1&&s2){s1.style.display='block';s2.style.display='none';} }
}
function lcSetCookie(tok){ try{ document.cookie='shop_customer_token='+encodeURIComponent(tok)+'; path=/; max-age='+(7*86400)+'; SameSite=Lax'; }catch(e){} }
var SPCAP=null;
// Şifremi unuttum / geri dönen müşteri → e-postaya link.
function lcForgot(){
var email=document.getElementById('ci-email').value.trim(), err=document.getElementById('ci-err2');
if(!/.+@.+\..+/.test(email)){ err.style.color='#f87171'; err.textContent='Enter your e-mail first.'; return; }
err.style.color='var(--wa-mut)'; err.textContent='Sending link…';
fetch('/api/v1/customer/forgot-password',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({email:email})})
.then(function(r){return r.json()}).then(function(j){ err.style.color='#34d399'; err.textContent=(j&&j.message)||'A reset link has been sent. Check inbox & spam.'; })
.catch(function(){ err.style.color='#f87171'; err.textContent='Something went wrong. Please try again.'; });
}
// GUEST: sadece başla (isim yok, hesap yok).
function guestStart(){
var email=document.getElementById('li-email').value.trim();
if(!/.+@.+\..+/.test(email)){alert('Please enter a valid e-mail.');return;}
startChat(email,'');
}
// CUSTOMER adım 1: e-posta gir → hesabı kontrol et.
function custContinue(){
var email=document.getElementById('ci-email').value.trim(), err=document.getElementById('ci-err'); err.style.color='#f87171'; err.textContent='';
if(!/.+@.+\..+/.test(email)){err.textContent='Please enter a valid e-mail.';return;}
err.style.color='var(--wa-mut)'; err.textContent='Checking…';
fetch('/api/v1/customer/check-email',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({email:email})})
.then(function(r){return r.json()}).then(function(j){
if(j&&j.exists){ // Kayıtlı, şifresi var → şifre iste.
err.textContent='';
document.getElementById('custStep1').style.display='none';
document.getElementById('custStep2').style.display='block';
document.getElementById('cust-hello').textContent='👋 Welcome back! Enter your password for '+email+'.';
document.getElementById('ci-pass').focus();
} else if(j&&j.hasOrders){ // Geri dönen müşteri, şifresi yok → mail ile şifre BELİRLEME linki.
err.style.color='var(--wa-mut)'; err.textContent='Sending you a link…';
fetch('/api/v1/customer/forgot-password',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({email:email})})
.then(function(r){return r.json()}).then(function(){ err.style.color='#34d399'; err.textContent='👋 Welcome back! We e-mailed you a link to set your password. Your previous orders are linked automatically. (Check inbox & spam.)'; });
} else { // Hesap/sipariş yok.
err.style.color='var(--wa-mut)'; err.textContent='No account or orders found for this e-mail. You can continue as a Guest instead. 👆';
}
}).catch(function(){ err.style.color='#f87171'; err.textContent='Something went wrong. Please try again.'; });
}
function custBack(){ document.getElementById('custStep2').style.display='none'; document.getElementById('custStep1').style.display='block'; document.getElementById('ci-pass').value=''; document.getElementById('ci-err2').textContent=''; }
// CUSTOMER adım 2: şifreyle giriş.
function custLogin(){
var email=document.getElementById('ci-email').value.trim(), pass=document.getElementById('ci-pass').value;
var err=document.getElementById('ci-err2'); err.style.color='#f87171'; err.textContent='';
if(!pass){err.textContent='Please enter your password.';return;}
fetch('/api/v1/customer/login',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({email:email,password:pass})})
.then(function(r){return r.json().then(function(j){return {ok:r.ok,j:j}})}).then(function(x){
if(!x.ok){err.textContent=(x.j&&x.j.message)||'Wrong password. Use "Forgot your password?" to reset it.';return;}
lcSetCookie(x.j.token); startChat(email,'');
}).catch(function(){err.textContent='Login failed.';});
}
function setPwSubmit(){
var email=document.getElementById('sp-email').value.trim(), pass=document.getElementById('sp-pass').value;
var ans=document.getElementById('sp-captcha-a').value, err=document.getElementById('sp-err'); err.textContent='';
if(!pass||pass.length<6){err.textContent='Password must be at least 6 characters.';return;}
fetch('/api/v1/customer/register',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({email:email,password:pass,captcha_token:SPCAP?SPCAP.token:'',captcha_answer:ans})})
.then(function(r){return r.json().then(function(j){return {ok:r.ok,j:j}})}).then(function(x){
if(!x.ok||!x.j.success){err.textContent=(x.j&&x.j.message)||'Please try again.';return;}
lcSetCookie(x.j.token); startChat(email,'');
}).catch(function(){err.textContent='Something went wrong.';});
}
function lcRequireLogin(email){
st.chatId=null;st.token=null;st.me=null;st.loggedIn=false;st.last=0;
if(st.pollTimer){clearInterval(st.pollTimer);st.pollTimer=null;}
document.getElementById('msgs').textContent='';
document.getElementById('chat').style.display='none';
document.getElementById('login').style.display='';
lcMode('cust');
document.getElementById('ci-email').value=email||'';
document.getElementById('ci-pass').value='';
document.getElementById('custStep1').style.display='none';
document.getElementById('custStep2').style.display='block';
document.getElementById('cust-hello').textContent='Enter your password to continue.';
document.getElementById('ci-pass').focus();
}
function lcResetGuest(){
st.chatId=null;st.token=null;st.me=null;st.loggedIn=false;st.last=0;st.lastDate='';st.loaded=false;st.seen=0;st.gonderildi={};st.waitingAI=false;
if(st.pollTimer){clearInterval(st.pollTimer);st.pollTimer=null;}
if(st.waitT){clearTimeout(st.waitT);st.waitT=null;}
try{localStorage.removeItem('sm_lc');}catch(e){}
document.getElementById('msgs').textContent='';
document.getElementById('chat').style.display='none';
document.getElementById('login').style.display='';
document.getElementById('li-email').value='';
document.getElementById('box').value='';
lcReplyKapat();
lcEmojiKapat();
document.getElementById('ci-email').value='';
document.getElementById('ci-pass').value='';
document.getElementById('orderInfoBar').style.display='none';
lcMode('guest');
}
function lcAccessResponse(j){
if(j&&j.redirect){window.top.location.replace('/');return true;}
if(j&&j.guestReset){lcResetGuest();return true;}
if(j&&j.loginRequired){lcRequireLogin(j.email);return true;}
return false;
}
function startChat(email,name){
email=email||document.getElementById('li-email').value.trim();
name=name||'';
if(!/.+@.+\..+/.test(email)){alert('Please enter a valid e-mail.');return}
try{localStorage.setItem('sm_lc',JSON.stringify({email:email,name:name}))}catch(e){}
fetch('/api/v1/livechat/start',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({email:email,name:name})})
.then(function(r){return r.json()}).then(function(j){
if(lcAccessResponse(j))return;
if(!j.chatId){alert(j.message||'Error');return}
st.chatId=j.chatId;st.token=j.token;st.ai=!!j.ai;st.loggedIn=!!j.loggedIn;
document.getElementById('login').style.display='none';
document.getElementById('chat').style.display='flex';
// "Sipariş bilgimi gönder" butonu yalnızca giriş yapmış müşteriye görünür.
if(st.loggedIn)document.getElementById('orderInfoBar').style.display='block';
offHoursNotice();
avLoad();
if(st.pollTimer)clearInterval(st.pollTimer);
poll();st.pollTimer=setInterval(poll,3000);
document.getElementById('box').focus();
});
}
function offHoursNotice(){
var nowUtc=new Date();
var h=(nowUtc.getUTCHours()+3)%24;
if(h>=3 && h<10){
var msgs=document.getElementById('msgs');
if(document.getElementById('offHours'))return;
var b=document.createElement('div');b.id='offHours';b.className='offhours';
b.textContent='⏰ Support may be limited between 03:00–10:00 (Istanbul time). Please leave your message and we\'ll get back to you shortly.';
msgs.appendChild(b);
}
}
var avState={value:'',palette:[]};
function avPaint(){
var b=document.getElementById('meAv');
if(!b)return;
if(/^\//.test(avState.value)) b.innerHTML='';
else b.textContent=avState.value||'🙂';
var g=document.getElementById('avGrid');
if(g) Array.prototype.forEach.call(g.children,function(el){
el.classList.toggle('on', el.getAttribute('data-v')===avState.value);
});
}
function avLoad(){
fetch('/api/v1/livechat/avatar?chatId='+st.chatId+'&token='+st.token)
.then(function(r){return r.json()}).then(function(j){
if(!j||!j.ok)return;
avState.value=j.avatar; avState.palette=j.palette||[];
var g=document.getElementById('avGrid');
if(g&&!g.children.length){
g.innerHTML=avState.palette.map(function(e){
return '';
}).join('');
}
avPaint();
}).catch(function(){});
}
function avToggle(){
var p=document.getElementById('avPanel');
p.style.display = p.style.display==='none' ? 'block' : 'none';
}
function avSet(v){
fetch('/api/v1/livechat/avatar',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({chatId:st.chatId,token:st.token,avatar:v})})
.then(function(r){return r.json()}).then(function(j){
if(j&&j.ok){ avState.value=j.avatar; avPaint(); document.getElementById('avPanel').style.display='none'; }
else alert((j&&j.message)||'Could not update.');
}).catch(function(){});
}
function avUpload(inp){
var f=inp.files&&inp.files[0];
if(!f)return;
var fd=new FormData();
fd.append('chatId',st.chatId); fd.append('token',st.token); fd.append('file',f);
fetch('/api/v1/livechat/avatar-upload',{method:'POST',body:fd})
.then(function(r){return r.json()}).then(function(j){
if(j&&j.ok){ avState.value=j.avatar; avPaint(); document.getElementById('avPanel').style.display='none'; }
else alert((j&&j.message)||'Upload failed.');
}).catch(function(){alert('Upload failed.')})
.finally(function(){ inp.value=''; });
}
function lcShake(){
var el=document.getElementById('chat');
if(!el)return;
el.classList.remove('lc-shake'); void el.offsetWidth; el.classList.add('lc-shake');
setTimeout(function(){el.classList.remove('lc-shake')},900);
try{ if(navigator.vibrate) navigator.vibrate([90,60,90]); }catch(e){}
}
function sendNudge(){
if(!st.chatId)return;
var b=document.getElementById('nudgeBtn');
if(b)b.disabled=true;
fetch('/api/v1/livechat/nudge',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({chatId:st.chatId,token:st.token})})
.then(function(r){return r.json()}).then(function(j){
if(j&&j.ok) lcShake();
else if(j&&j.wait) alert('Please wait '+j.wait+'s before nudging again.');
}).catch(function(){})
.finally(function(){ setTimeout(function(){ if(b)b.disabled=false; },3000); });
}
function poll(){
if(!st.chatId)return;
fetch('/api/v1/livechat/messages?chatId='+st.chatId+'&token='+st.token+'&after='+st.last)
.then(function(r){return r.json()}).then(function(j){
if(lcAccessResponse(j))return;
// Ekip yazıyor mu + AI cevabı bekleniyor mu (ikisinden biri → üç nokta)
var at=document.getElementById('agentTyping');
if(at)at.classList.toggle('on',!!j.agent_typing||!!st.waitingAI);
// Bizim mesajlarimiz nereye kadar okundu -> tikler
if(typeof j.seen_id==='number'&&j.seen_id!==st.seen){st.seen=j.seen_id;paintTicks();}
if(j.nudge) lcShake();
if(!j.messages||!j.messages.length)return;
var hadNewFromSupport=false;
j.messages.forEach(function(m){add(m);st.last=Math.max(st.last,m.id);if(m.sender!=='customer')hadNewFromSupport=true;else st.gonderildi[String(m.body||'').trim()]=Date.parse((m.created_at||'').replace(' ','T')+'Z')||Date.now();});
if(j.reactions) lcTepkiCiz(j.reactions);
if(hadNewFromSupport){st.waitingAI=false;if(st.waitT)clearTimeout(st.waitT);var at2=document.getElementById('agentTyping');if(at2)at2.classList.remove('on');}
// İlk yükleme sesli değil; sonraki turlarda ekipten yeni mesaj + başka sekmedeyse tatlı ses.
if(st.loaded && hadNewFromSupport && document.hidden) lcChime();
st.loaded=true;
paintTicks();
scrollDown();
});
}
function lcChime(){
try{
var C=window.AudioContext||window.webkitAudioContext; if(!C)return;
var c=new C();
[[880,0],[1174,.13]].forEach(function(p){
var o=c.createOscillator(),g=c.createGain();
o.type='sine';o.frequency.value=p[0];
o.connect(g);g.connect(c.destination);
var t=c.currentTime+p[1];
g.gain.setValueAtTime(0,t);g.gain.linearRampToValueAtTime(.18,t+.03);
g.gain.exponentialRampToValueAtTime(.0001,t+.35);
o.start(t);o.stop(t+.36);
});
setTimeout(function(){try{c.close()}catch(e){}},900);
}catch(e){}
}
/* Gonderdigimiz mesajlarda tik: bir tik = iletildi, iki mavi tik = okundu. */
function paintTicks(){
var els=document.querySelectorAll('#msgs .m.out[data-id]');
for(var i=0;iNo orders found on your account.
';return;}
box.innerHTML='';
os.forEach(function(o){
var prod=(o.products&&o.products.length)?o.products.join(', '):'Order';
var b=document.createElement('button');b.className='ord-pick';
b.innerHTML='
';});
}
function lcSendOrder(o){
document.getElementById('ordModal').style.display='none';
var prod=(o.products&&o.products.length)?o.products.join(', '):'Order';
var body='🧾 My order info\nOrder no: #'+o.unique_id+'\nProduct: '+prod+'\nPrice: '+o.total+' '+(o.currency||'')+'\nStatus: '+o.status;
if(st.sonMetin===body && (Date.now()-st.sonMetinT)<10000)return; // çift tık
st.sonMetin=body;st.sonMetinT=Date.now();
fetch('/api/v1/livechat/send',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({chatId:st.chatId,token:st.token,body:body})}).then(poll);
}
function lcUnsend(id,el){
if(!confirm('Unsend this message?'))return;
fetch('/api/v1/livechat/unsend',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({chatId:st.chatId,token:st.token,messageId:id})})
.then(function(r){return r.json()}).then(function(j){
if(j&&j.ok){ if(el&&el.parentNode)el.parentNode.removeChild(el); }
else alert((j&&j.message)||'Could not unsend.');
}).catch(function(){alert('Could not unsend.');});
}
// dosya ekleme + sürükle-bırak
(function(){
var fi=document.getElementById('fileInput'),ab=document.getElementById('attachBtn'),chatEl=document.getElementById('chat'),hint=document.getElementById('dropHint');
if(ab&&fi){ab.onclick=function(){fi.click()};fi.onchange=function(e){uploadFiles(e.target.files);e.target.value=''};}
if(chatEl){
var dc=0;
chatEl.addEventListener('dragenter',function(e){e.preventDefault();dc++;hint.classList.add('on')});
chatEl.addEventListener('dragover',function(e){e.preventDefault()});
chatEl.addEventListener('dragleave',function(e){e.preventDefault();dc--;if(dc<=0)hint.classList.remove('on')});
chatEl.addEventListener('drop',function(e){e.preventDefault();dc=0;hint.classList.remove('on');if(e.dataTransfer&&e.dataTransfer.files&&e.dataTransfer.files.length)uploadFiles(e.dataTransfer.files)});
}
})();
// Giriş YAPMIŞ müşteri → doğrudan sohbet (sunucu son 30 dk açık sohbeti sürdürür).
// Giriş YAPMAMIŞ → misafir/üye SEÇİM EKRANI gösterilir; sohbet OTOMATİK açılmaz.
// (Önceki misafir e-postası varsa sadece alanı doldurur — otomatik başlatmaz.)
(function(){
if(st.me&&st.me.email){startChat(st.me.email,st.me.name||'');return}
var requiredEmail="";
if(requiredEmail==='priyankvlogs@gmail.com'){lcResetGuest();return;}
if(requiredEmail){lcRequireLogin(requiredEmail);return;}
try{
var s=JSON.parse(localStorage.getItem('sm_lc')||'null');
if(s&&s.email){ var el=document.getElementById('li-email'); if(el)el.value=s.email; }
}catch(e){}
try{ lcMode('guest'); }catch(e){}
})();
// Profilden "🔑 Giriş kodu al" ile gelindiyse: sipariş + hesap önceden dolu,
// sohbet hazır olunca AI'ya otomatik sorar (kodu verir ya da süresi bittiyse yönlendirir).
(function(){
var p=new URLSearchParams(location.search);
var co=p.get('code_order'); if(!co) return;
var acct=p.get('code_account')||'', svc=p.get('code_service')||'';
var intro='Hi, can I get my login code for '+(svc||'my account')+(acct?(' ('+acct+')'):'')+' in order #'+co+'?';
try{
p.delete('code_order'); p.delete('code_account'); p.delete('code_service');
var qs=p.toString();
history.replaceState(null,'',location.pathname+(qs?('?'+qs):'')+location.hash);
}catch(e){}
var tries=0, iv=setInterval(function(){
// st.loaded → ilk poll bitti, geçmiş mesajlar elimizde; ona bakarak karar veriyoruz.
if(st.chatId && st.loaded){
clearInterval(iv);
var box=document.getElementById('box'); if(!box) return;
box.value=intro; boxGrow(box);
var onceki=st.gonderildi[intro];
if(onceki && (Date.now()-onceki) < 6*3600*1000){ box.focus(); return; } // zaten sordu
sendMsg();
}
else if(++tries>80){ clearInterval(iv); }
},150);
})();
(function(){
var p=new URLSearchParams(location.search);
var tp=(p.get('tp_order')||'').replace(/[^A-Za-z0-9]/g,'').slice(0,32);
var po=(p.get('pay_order')||'').replace(/[^A-Za-z0-9]/g,'').slice(0,32);
if(!tp && !po) return;
try{ p.delete('tp_order'); p.delete('pay_order'); var qs=p.toString(); history.replaceState(null,'',location.pathname+(qs?('?'+qs):'')+location.hash); }catch(e){}
var msg=po ? ('Hi! I had a problem paying by card for order #'+po+'. Can you help me complete my order?')
: ('Hi! I posted a Trustpilot review for order #'+tp+' but my screenshot could not be verified automatically. Attaching the screenshot here.');
var tries=0, iv=setInterval(function(){
if(st.chatId && st.loaded){
clearInterval(iv);
var box=document.getElementById('box'); if(!box) return;
if(!box.value){ box.value=msg; boxGrow(box); }
box.focus();
}
else if(++tries>80){ clearInterval(iv); }
},150);
})();