/* OK ITHAKI V249386
   One friendship gate for every personal message, voice call, video call,
   DM file/photo/video/audio send and direct-message payload.
   Server-side V249380 friendship enforcement remains authoritative. */
(function(){
  'use strict';
  const BUILD='V249386_GLOBAL_FRIENDSHIP_GATE_ALL_COMMUNICATION';
  if(window.__ITHAKI_V249386_GLOBAL_FRIEND_GATE__)return;
  window.__ITHAKI_V249386_GLOBAL_FRIEND_GATE__=1;

  const $=id=>document.getElementById(id);
  const esc=v=>String(v==null?'':v).replace(/[&<>"']/g,ch=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[ch]));
  const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
  const PENDING_KEY='ith_pending_global_friend_action_v249386';
  const CACHE_MS=15000;
  const base={};
  const wrappers={};
  const acceptedCache=new Map();
  let pending=null;
  let pendingExecutor=null;
  let pollTimer=0;
  let installed=false;

  function appState(){try{return typeof state!=='undefined'&&state?state:(window.state||{})}catch(e){return window.state||{}}}
  function room(){const s=appState();return String(s.room||localStorage.getItem('ith_room')||'ithaki-phone-test')}
  function device(){const s=appState();return String(localStorage.getItem('ith_device')||s.device||'').trim()}
  function registered(){
    const s=appState();const name=String(s.name||localStorage.getItem('ith_name')||'Μέλος').trim().toLocaleLowerCase('el');
    return !!device()&&localStorage.getItem('ith_registered_member_v249154')==='1'&&localStorage.getItem('ith_age16')==='1'&&localStorage.getItem('ith_policy_ok')==='1'&&name!=='μέλος'&&name!=='member'
  }
  function person(peerId,meta){
    peerId=String(peerId||'');meta=meta||{};let p=null;const s=appState();
    try{p=s.people&&typeof s.people.get==='function'?s.people.get(peerId):null}catch(e){}
    return {id:peerId,name:String((p&&p.nickname)||meta.name||meta.nickname||'Μέλος'),avatar:String((p&&p.avatar)||meta.avatar||'')}
  }
  function initials(name){const parts=String(name||'Μ').trim().split(/\s+/).filter(Boolean);return esc((parts[0]?.[0]||'Μ')+(parts[1]?.[0]||''))}
  function avatarHtml(p){return p.avatar?`<img src="${esc(p.avatar)}" alt="">`:initials(p.name)}
  function actionLabel(action){return action==='video'?'βιντεοκλήση':action==='voice'?'φωνητική κλήση':action==='file'?'αρχείο σε μήνυμα':action==='photo'?'φωτογραφία σε μήνυμα':action==='audio'?'ηχητικό μήνυμα':'μήνυμα'}
  function notice(text,ms=5500){try{if(typeof toast==='function')toast(String(text),ms);else if(window.ITH&&typeof ITH.notifyAppEvent==='function')ITH.notifyAppEvent(String(text));else alert(String(text))}catch(e){console.log(text)}}
  async function jsonFetch(path,options){
    const r=await fetch(path,Object.assign({cache:'no-store',credentials:'same-origin'},options||{}));let d={};try{d=await r.json()}catch(e){}
    if(!r.ok||!d||d.ok===false)throw new Error(String((d&&(d.note||d.message||d.detail))||('HTTP '+r.status)));
    return d
  }
  async function friendState(peerId,force){
    peerId=String(peerId||'');const key=room()+'|'+device()+'|'+peerId,hit=acceptedCache.get(key);
    if(!force&&hit&&Date.now()-hit.at<CACHE_MS)return hit.data;
    const aliases=(window.ITH&&typeof ITH.accountDeviceCandidatesV249386==='function'?(ITH.accountDeviceCandidatesV249386()||[]):[]).filter(x=>String(x||'')&&String(x)!==device()).join(',');const d=await jsonFetch('/api/social/friend/state_v249390?room_id='+encodeURIComponent(room())+'&device_id='+encodeURIComponent(device())+'&peer_id='+encodeURIComponent(peerId)+'&aliases='+encodeURIComponent(aliases)+'&_v='+Date.now());if(d.peer){try{const s=appState();if(s.people&&typeof s.people.set==='function')s.people.set(peerId,Object.assign({},s.people.get(peerId)||{},d.peer,{id:peerId,device_id:peerId}))}catch(e){}}
    if(d.accepted&&d.communication_allowed!==false)acceptedCache.set(key,{at:Date.now(),data:d});else acceptedCache.delete(key);
    return d
  }
  async function sendFriendRequest(p){
    const s=appState();
    return jsonFetch('/api/social/friend/request_v249390',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({room_id:room(),from_id:device(),from_name:String(s.name||localStorage.getItem('ith_name')||'Μέλος'),to_id:p.id,to_name:p.name})})
  }
  function ensureCss(){
    if($('ithGlobalFriendCss386'))return;
    const st=document.createElement('style');st.id='ithGlobalFriendCss386';st.textContent=`
      #ithGlobalFriendGate386{position:fixed;z-index:2147483647;inset:0;background:rgba(0,0,0,.82);display:grid;place-items:center;padding:14px;backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px)}
      #ithGlobalFriendGate386[hidden]{display:none!important}.ithGlobalFriendBox386{width:min(560px,96vw);max-height:88vh;overflow:auto;border:1px solid rgba(255,218,119,.44);border-radius:25px;background:radial-gradient(circle at 12% 0,rgba(255,213,94,.16),transparent 34%),linear-gradient(155deg,#071521,#02070d);color:#fff;padding:17px;font-family:system-ui;box-shadow:0 30px 100px rgba(0,0,0,.82)}
      .ithGlobalFriendHead386{display:grid;grid-template-columns:64px minmax(0,1fr) auto;gap:11px;align-items:center}.ithGlobalFriendAvatar386{width:64px;height:64px;border-radius:22px;overflow:hidden;display:grid;place-items:center;border:1px solid rgba(255,224,142,.5);background:rgba(255,255,255,.08);color:#ffe09a;font-size:24px;font-weight:1000}.ithGlobalFriendAvatar386 img{width:100%;height:100%;object-fit:cover}.ithGlobalFriendHead386 h2{margin:0;color:#ffe09a;font-size:20px}.ithGlobalFriendHead386 p{margin:4px 0 0;color:rgba(240,248,255,.72);font-size:12px}.ithGlobalFriendClose386{width:42px;height:42px;border-radius:14px;border:1px solid rgba(255,255,255,.16);background:rgba(255,255,255,.07);color:#fff;font-size:22px}.ithGlobalFriendText386{margin-top:13px;padding:12px;border-radius:17px;border:1px solid rgba(255,217,110,.2);background:rgba(255,255,255,.055);line-height:1.5}.ithGlobalFriendStatus386{margin-top:9px;color:#ffe09a;font-size:12px;min-height:18px}.ithGlobalFriendButtons386{display:flex;gap:8px;flex-wrap:wrap;margin-top:12px}.ithGlobalFriendButtons386 button{min-height:44px;border-radius:999px;padding:9px 15px;border:1px solid rgba(255,255,255,.17);background:rgba(255,255,255,.07);color:#fff;font-weight:950}.ithGlobalFriendButtons386 .gold{border-color:#f1cf77;background:linear-gradient(135deg,#9f681c,#f1cf77);color:#1b1104}.ithGlobalFriendButtons386 button:disabled{opacity:.55}
    `;document.head.appendChild(st)
  }
  function ensureModal(){
    let modal=$('ithGlobalFriendGate386');if(modal)return modal;ensureCss();
    modal=document.createElement('div');modal.id='ithGlobalFriendGate386';modal.hidden=true;
    modal.innerHTML='<div class="ithGlobalFriendBox386"><div class="ithGlobalFriendHead386"><div id="ithGlobalFriendAvatar386" class="ithGlobalFriendAvatar386">Μ</div><div><h2 id="ithGlobalFriendTitle386">Έλεγχος φιλίας</h2><p id="ithGlobalFriendName386">Μέλος</p></div><button id="ithGlobalFriendClose386" class="ithGlobalFriendClose386" type="button">×</button></div><div id="ithGlobalFriendText386" class="ithGlobalFriendText386"></div><div id="ithGlobalFriendStatus386" class="ithGlobalFriendStatus386"></div><div class="ithGlobalFriendButtons386"><button id="ithGlobalFriendPrimary386" class="gold" type="button">Αίτημα φιλίας</button><button id="ithGlobalFriendCancel386" type="button">Κλείσιμο</button></div></div>';
    document.body.appendChild(modal);
    $('ithGlobalFriendClose386').onclick=closeGate;$('ithGlobalFriendCancel386').onclick=closeGate;
    modal.addEventListener('click',e=>{if(e.target===modal)closeGate()});
    return modal
  }
  function closeGate(){const m=$('ithGlobalFriendGate386');if(m)m.hidden=true}
  function persistPending(value){
    pending=value||null;
    try{if(pending&&['message','video','voice'].includes(pending.action))localStorage.setItem(PENDING_KEY,JSON.stringify({action:pending.action,peerId:pending.peer.id,peerName:pending.peer.name,peerAvatar:pending.peer.avatar,expiresAt:Date.now()+15*60*1000}));else localStorage.removeItem(PENDING_KEY)}catch(e){}
  }
  function loadPending(){
    try{
      let raw=localStorage.getItem(PENDING_KEY)||'';
      if(!raw){raw=localStorage.getItem('ith_pending_global_friend_action_v249385')||'';if(raw){localStorage.setItem(PENDING_KEY,raw);localStorage.removeItem('ith_pending_global_friend_action_v249385')}}
      const x=JSON.parse(raw||'null');
      if(!x||!x.peerId||!x.action||Number(x.expiresAt||0)<Date.now()){localStorage.removeItem(PENDING_KEY);return null}
      return{action:String(x.action),peer:person(x.peerId,{name:x.peerName,avatar:x.peerAvatar}),executor:null,args:[]}
    }catch(e){return null}
  }
  function clearPending(){persistPending(null);pendingExecutor=null;clearTimeout(pollTimer);pollTimer=0}
  function openNotifications(){closeGate();try{if(window.ITH&&typeof ITH.notifyCenter==='function')return ITH.notifyCenter();if(typeof notifyCenter==='function')return notifyCenter();if(window.ITH&&typeof ITH.page==='function')return ITH.page('home')}catch(e){}return false}
  function renderGate(state){
    const modal=ensureModal(),p=pending.peer,action=pending.action,label=actionLabel(action),primary=$('ithGlobalFriendPrimary386');
    $('ithGlobalFriendAvatar386').innerHTML=avatarHtml(p);$('ithGlobalFriendName386').textContent=p.name;primary.hidden=false;primary.disabled=false;primary.dataset.mode='request';$('ithGlobalFriendStatus386').textContent='';
    if(state.blocked){$('ithGlobalFriendTitle386').textContent='Η επικοινωνία δεν είναι διαθέσιμη';$('ithGlobalFriendText386').textContent='Υπάρχει ενεργό μπλοκάρισμα μεταξύ των δύο μελών.';primary.hidden=true}
    else if(state.pending_incoming){$('ithGlobalFriendTitle386').textContent='Υπάρχει αίτημα προς αποδοχή';$('ithGlobalFriendText386').textContent=`Το μέλος έχει ήδη στείλει αίτημα. Αποδέξου το από τις ειδοποιήσεις και μετά θα ανοίξει η ${label}.`;primary.textContent='Άνοιγμα ειδοποιήσεων';primary.dataset.mode='notifications'}
    else if(state.pending_outgoing){$('ithGlobalFriendTitle386').textContent='Περιμένει αποδοχή';$('ithGlobalFriendText386').textContent=`Το αίτημα φιλίας έχει σταλεί. Μόλις γίνει αποδοχή, θα ανοίξει αυτόματα η ${label}.`;primary.textContent='Περιμένει αποδοχή';primary.dataset.mode='waiting';primary.disabled=true;startPolling()}
    else{$('ithGlobalFriendTitle386').textContent='Χρειάζεται αποδοχή φιλίας';$('ithGlobalFriendText386').textContent=`Για να στείλεις ${label}, πρέπει πρώτα να γίνετε φίλοι. Να σταλεί αίτημα φιλίας;`;primary.textContent='Στείλε αίτημα φιλίας';primary.dataset.mode='request'}
    primary.onclick=confirmGate;modal.hidden=false
  }
  async function confirmGate(){
    const primary=$('ithGlobalFriendPrimary386'),status=$('ithGlobalFriendStatus386'),mode=String(primary.dataset.mode||'request');
    if(mode==='notifications')return openNotifications();if(mode==='waiting')return false;
    primary.disabled=true;status.textContent='Στέλνω το αίτημα φιλίας…';
    try{
      const d=await sendFriendRequest(pending.peer);
      if(d.already_friends){status.textContent='Η φιλία είναι ήδη ενεργή.';acceptedCache.clear();setTimeout(checkPendingNow,120);return false}
      if(d.reverse_pending){status.textContent='Υπάρχει αίτημα από το άλλο μέλος. Άνοιξε τις ειδοποιήσεις.';primary.disabled=false;primary.textContent='Άνοιγμα ειδοποιήσεων';primary.dataset.mode='notifications';return false}
      status.textContent=d.duplicate?'Το αίτημα υπάρχει ήδη και περιμένει αποδοχή.':'Το αίτημα στάλθηκε και περιμένει αποδοχή.';primary.textContent='Περιμένει αποδοχή';primary.dataset.mode='waiting';startPolling()
    }catch(e){status.textContent=String(e.message||e);primary.disabled=false;primary.textContent='Επανάληψη αιτήματος'}
    return false
  }
  async function executePending(){
    if(!pending)return false;const current=pending,executor=pendingExecutor||current.executor;clearPending();closeGate();
    notice('Η φιλία έγινε αποδεκτή. Ανοίγω την επικοινωνία…',4200);
    try{
      if(typeof executor==='function')return await executor();
      if(current.action==='message')return await callBaseStartDM(current.peer.id);
      if(current.action==='video'){await callBaseStartDM(current.peer.id);return await callBaseVideo()}
      if(current.action==='voice'){await callBaseStartDM(current.peer.id);return await callBaseVoice()}
    }catch(e){notice(e.message||e,7000)}
    return false
  }
  async function checkPendingNow(){
    if(!pending)return false;
    try{const st=await friendState(pending.peer.id,true);if(st.accepted&&st.communication_allowed!==false){await executePending();return true}renderGate(st)}catch(e){const status=$('ithGlobalFriendStatus386');if(status)status.textContent='Δεν ολοκληρώθηκε ο έλεγχος. Θα επαναληφθεί.'}
    return false
  }
  function startPolling(){clearTimeout(pollTimer);const tick=async()=>{if(!pending)return;const done=await checkPendingNow();if(!done&&pending)pollTimer=setTimeout(tick,5000)};pollTimer=setTimeout(tick,1200)}
  async function gate(action,peerId,executor,meta){
    peerId=String(peerId||'');
    if(!registered()){notice('Χρειάζεται αποθηκευμένο προφίλ μέλους πριν από προσωπική επικοινωνία.',7000);try{window.ITH&&ITH.page&&ITH.page('profile')}catch(e){}return false}
    if(!peerId){notice('Διάλεξε πρώτα μέλος.',5000);return false}
    if(peerId===device()){notice('Δεν γίνεται προσωπική επικοινωνία με τον εαυτό σου.');return false}
    const p=person(peerId,meta);pending={action:String(action||'message'),peer:p,executor,args:[]};pendingExecutor=executor;persistPending(pending);
    try{const st=await friendState(peerId,false);if(st.accepted&&st.communication_allowed!==false)return executePending();renderGate(st)}catch(e){renderGate({});$('ithGlobalFriendStatus386').textContent='Δεν ολοκληρώθηκε ο έλεγχος φιλίας: '+String(e.message||e)}
    return false
  }
  function activePeer(){const s=appState();return String(s.activePeer||pending?.peer?.id||'')}
  function peerFromChannel(channel){const parts=String(channel||'').split(':');if(parts[0]!=='dm'||parts.length<3)return'';const me=device();return String(parts.slice(1).find(x=>String(x)!==me)||'')}
  function isOur(fn){return !!(fn&&fn.__v249386GlobalFriendGate)}
  function capture(name,fn){if(typeof fn==='function'&&!isOur(fn))base[name]=fn}
  function callBaseStartDM(id){const fn=base.startDM||base.windowStartDM;if(typeof fn!=='function')throw new Error('Τα Μηνύματα δεν είναι διαθέσιμα.');return Promise.resolve(fn.call(window.ITH||window,id))}
  function callBaseVideo(){const fn=base.startVideoCall||base.windowStartVideoCall;if(typeof fn!=='function')throw new Error('Η βιντεοκλήση δεν είναι διαθέσιμη.');return Promise.resolve(fn.call(window.ITH||window))}
  function callBaseVoice(){const fn=base.startVoiceCall||base.windowStartVoiceCall;if(typeof fn!=='function')throw new Error('Η φωνητική κλήση δεν είναι διαθέσιμη.');return Promise.resolve(fn.call(window.ITH||window))}
  function marked(fn){fn.__v249386GlobalFriendGate=true;return fn}

  wrappers.startDM=marked(function(id){const args=arguments,p=person(id);return gate('message',id,()=>{const fn=base.startDM||base.windowStartDM;if(typeof fn!=='function')throw new Error('Τα Μηνύματα δεν είναι διαθέσιμα.');return fn.apply(this,args)},p)});
  wrappers.startVideoCall=marked(function(){const args=arguments,peer=activePeer();return gate('video',peer,async()=>{if(String(appState().activePeer||'')!==peer)await callBaseStartDM(peer);const fn=base.startVideoCall||base.windowStartVideoCall;if(typeof fn!=='function')throw new Error('Η βιντεοκλήση δεν είναι διαθέσιμη.');return fn.apply(this,args)},person(peer))});
  wrappers.startVoiceCall=marked(function(){const args=arguments,peer=activePeer();return gate('voice',peer,async()=>{if(String(appState().activePeer||'')!==peer)await callBaseStartDM(peer);const fn=base.startVoiceCall||base.windowStartVoiceCall;if(typeof fn!=='function')throw new Error('Η φωνητική κλήση δεν είναι διαθέσιμη.');return fn.apply(this,args)},person(peer))});
  wrappers.sendDMText=marked(function(){const args=arguments,peer=activePeer(),fn=base.sendDMText||base.windowSendDMText;if(typeof fn!=='function')return false;return gate('message',peer,()=>fn.apply(this,args),person(peer))});
  wrappers.openMessageCamera=marked(function(kind){const args=arguments,peer=activePeer(),fn=base.openMessageCamera||base.windowOpenMessageCamera;if(typeof fn!=='function')return false;return gate(kind==='video'?'video':'photo',peer,()=>fn.apply(this,args),person(peer))});
  wrappers.startAudioRecording=marked(function(ctx){const args=arguments,fn=base.startAudioRecording||base.windowStartAudioRecording;if(typeof fn!=='function')return false;if(String(ctx||'')!=='dm')return fn.apply(this,args);const peer=activePeer();return gate('audio',peer,()=>fn.apply(this,args),person(peer))});
  wrappers.sendPreview=marked(function(){const args=arguments,fn=base.sendPreview||base.windowSendPreview;if(typeof fn!=='function')return false;const s=appState(),preview=s.preview||{};if(String(preview.ctx||'')!=='dm')return fn.apply(this,args);const peer=activePeer();return gate(preview.kind==='video'?'video':preview.kind==='photo'?'photo':'file',peer,()=>fn.apply(this,args),person(peer))});
  wrappers.sendMessagePayload=marked(function(channel){const args=arguments,fn=base.windowSendMessagePayload;if(typeof fn!=='function')return Promise.reject(new Error('Η αποστολή μηνύματος δεν είναι διαθέσιμη.'));const peer=peerFromChannel(channel);if(!peer)return fn.apply(this,args);return gate('message',peer,()=>fn.apply(this,args),person(peer))});
  wrappers.sendCallRequest=marked(function(kind){const args=arguments,fn=base.windowSendCallRequest;if(typeof fn!=='function')return false;const peer=activePeer();return gate(String(kind)==='video'?'video':'voice',peer,()=>fn.apply(this,args),person(peer))});

  function wrapObject(obj,key,baseKey,wrapper){if(!obj)return;const current=obj[key];if(typeof current==='function'&&!isOur(current))capture(baseKey,current);if(obj[key]!==wrapper){try{obj[key]=wrapper}catch(e){}}}
  function wrapDirectDmAlias(obj,key,baseKey){
    if(!obj)return;
    const current=obj[key];if(typeof current==='function'&&!isOur(current))capture(baseKey,current);
    if(!wrappers[baseKey])wrappers[baseKey]=marked(function(id){
      const args=arguments,p=person(id),fn=base[baseKey];
      if(typeof fn!=='function')return false;
      return gate('message',id,()=>fn.apply(this,args),p)
    });
    if(typeof base[baseKey]==='function'&&obj[key]!==wrappers[baseKey]){try{obj[key]=wrappers[baseKey]}catch(e){}}
  }
  function wrapAcceptance(obj,key,baseKey){
    if(!obj)return;
    const current=obj[key];if(typeof current==='function'&&!isOur(current))capture(baseKey,current);
    if(!wrappers[baseKey])wrappers[baseKey]=marked(function(){
      const args=arguments,fn=base[baseKey];if(typeof fn!=='function')return false;
      const finish=value=>{acceptedCache.clear();try{window.dispatchEvent(new CustomEvent('ithaki-friend-accepted-v249386'))}catch(e){}setTimeout(()=>pending&&checkPendingNow(),180);return value};
      try{const out=fn.apply(this,args);return out&&typeof out.then==='function'?out.then(finish):finish(out)}catch(e){throw e}
    });
    if(typeof base[baseKey]==='function'&&obj[key]!==wrappers[baseKey]){try{obj[key]=wrappers[baseKey]}catch(e){}}
  }
  function installWrappers(){
    window.ITH=window.ITH||{};
    wrapObject(window.ITH,'startDM','startDM',wrappers.startDM);wrapObject(window,'startDM','windowStartDM',wrappers.startDM);
    wrapObject(window.ITH,'startVideoCall','startVideoCall',wrappers.startVideoCall);wrapObject(window,'startVideoCall','windowStartVideoCall',wrappers.startVideoCall);
    wrapObject(window.ITH,'startVoiceCall','startVoiceCall',wrappers.startVoiceCall);wrapObject(window,'startVoiceCall','windowStartVoiceCall',wrappers.startVoiceCall);
    wrapObject(window.ITH,'sendDMText','sendDMText',wrappers.sendDMText);wrapObject(window,'sendDMText','windowSendDMText',wrappers.sendDMText);
    wrapObject(window.ITH,'openMessageCamera','openMessageCamera',wrappers.openMessageCamera);wrapObject(window,'openMessageCamera','windowOpenMessageCamera',wrappers.openMessageCamera);
    wrapObject(window.ITH,'startAudioRecording','startAudioRecording',wrappers.startAudioRecording);wrapObject(window,'startAudioRecording','windowStartAudioRecording',wrappers.startAudioRecording);
    wrapObject(window.ITH,'sendPreview','sendPreview',wrappers.sendPreview);wrapObject(window,'sendPreview','windowSendPreview',wrappers.sendPreview);
    wrapObject(window,'sendMessagePayload','windowSendMessagePayload',wrappers.sendMessagePayload);
    wrapObject(window,'sendCallRequest','windowSendCallRequest',wrappers.sendCallRequest);
    ['openDM','openDM310','openDMV249235','v249247OpenDmFromNotice','openLinkedDmFromUrlV249227'].forEach(name=>{
      wrapDirectDmAlias(window.ITH,name,'ithAlias_'+name);wrapDirectDmAlias(window,name,'windowAlias_'+name)
    });
    ['acceptContact','respondFriendProposalV249223','respondFriendProposalV249233'].forEach(name=>{
      wrapAcceptance(window.ITH,name,'ithAccept_'+name);wrapAcceptance(window,name,'windowAccept_'+name)
    });
    Object.assign(window.ITH,{guardFriendCommunicationV249386:gate,checkFriendStateV249386:friendState,openGlobalFriendGateV249386:(action,id,meta)=>gate(action,id,null,meta),resumePendingFriendCommunicationV249386:resumePending,friendAcceptedRecheckV249386:()=>{acceptedCache.clear();return pending?checkPendingNow():false}});
  }
  function resumePending(){
    if(pending)return;const saved=loadPending();if(!saved)return;pending=saved;pendingExecutor=null;startPolling()
  }
  function install(){
    if(installed)return;installed=true;ensureCss();ensureModal();installWrappers();resumePending();
    setInterval(installWrappers,1200);
    window.addEventListener('focus',()=>{installWrappers();acceptedCache.clear();if(pending)checkPendingNow()});
    window.addEventListener('online',()=>{acceptedCache.clear();if(pending)checkPendingNow()});
    window.addEventListener('ithaki-friend-accepted-v249386',()=>{acceptedCache.clear();if(pending)checkPendingNow()});
    document.addEventListener('visibilitychange',()=>{if(!document.hidden){acceptedCache.clear();if(pending)checkPendingNow()}});
    document.addEventListener('click',ev=>{
      const el=ev.target&&ev.target.closest?ev.target.closest('[data-ithaki-peer-action][data-peer-id]'):null;if(!el)return;
      const action=String(el.getAttribute('data-ithaki-peer-action')||'message'),id=String(el.getAttribute('data-peer-id')||'');
      if(!id||!['message','video','voice'].includes(action))return;
      ev.preventDefault();ev.stopPropagation();
      gate(action,id,null,{name:el.getAttribute('data-peer-name')||'',avatar:el.getAttribute('data-peer-avatar')||''})
    },true);
    document.documentElement.setAttribute('data-ithaki-global-friend-gate','V249386');
    document.documentElement.setAttribute('data-ithaki-friend-continuation','message-voice-video-after-acceptance');
  }
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',install,{once:true});else install();
})();
