/* OK ITHAKI V249396 — professional conversation security modes and Tor-ready profile panel.
 * Modes:
 * 1) full_e2ee: Android Keystore RSA-OAEP + per-message AES-256-GCM.
 * 2) standard_aes: shared-secret AES-GCM using WebCrypto (faster, both friends need the same key).
 * 3) no_encryption: plaintext content on the server, protected in transit only by HTTPS.
 * The UI never presents Tor or anonymity as active before native proxy routing is implemented and verified.
 */
(() => {
  'use strict';
  if (window.__ITHAKI_V249396_PRO_SECURITY__) return;
  window.__ITHAKI_V249396_PRO_SECURITY__ = 1;

  const VERSION = 'V249396-professional-security-modes-tor-ready';
  const FULL = 'full_e2ee';
  const STANDARD = 'standard_aes';
  const NONE = 'no_encryption';
  const MODES = {
    [FULL]: { icon:'🔐', title:'Πλήρης ασφάλεια', short:'Πλήρης E2EE', tone:'full', detail:'Android Keystore · RSA-OAEP · AES-256-GCM · ο server δεν έχει κλειδί αποκρυπτογράφησης.' },
    [STANDARD]: { icon:'🔒', title:'Κανονική κρυπτογράφηση', short:'AES-GCM γρήγορη', tone:'standard', detail:'Κοινός μυστικός κωδικός και AES-GCM. Και οι δύο φίλοι πρέπει να έχουν ακριβώς τον ίδιο ισχυρό κωδικό.' },
    [NONE]: { icon:'⚠️', title:'Χωρίς κρυπτογράφηση περιεχομένου', short:'Χωρίς E2EE', tone:'none', detail:'Το περιεχόμενο αποθηκεύεται αναγνώσιμο στον server. Η μεταφορά εξακολουθεί να προστατεύεται από HTTPS.' }
  };
  const modeCache = new Map();
  let original = null;
  let lastChannel = '';
  let panelBusy = false;

  const $ = id => document.getElementById(id);
  const esc = v => String(v == null ? '' : v).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
  const sleep = ms => new Promise(r => setTimeout(r, ms));
  function appState(){ try { return window.state || 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') || localStorage.getItem('device_id') || s.device || '').trim(); }
  function nickname(){ const s=appState(); return String(s.name || localStorage.getItem('ith_name') || 'Μέλος'); }
  function apiBase(){ const s=appState(); return String(s.api || location.origin || 'https://ok-ithaki.gr').replace(/\/+$/, ''); }
  function activeChannel(){ const s=appState(); return String(s.activeChannel || ''); }
  function peerFromChannel(channel){ const parts=String(channel||'').split(':'); if(parts.length!==3||parts[0]!=='dm')return''; const me=device(); return parts[1]===me?parts[2]:(parts[2]===me?parts[1]:''); }
  function modeKey(channel){ return 'ith_conversation_security_mode_v249396:' + room() + ':' + String(channel||''); }
  function ackKey(channel){ return 'ith_plaintext_ack_v249396:' + room() + ':' + String(channel||''); }
  function sharedKeyName(channel){ return 'ith_e2e_key_' + String(channel||'main'); }
  function parseJson(value, fallback={}){ try { return JSON.parse(String(value||'')); } catch(e) { return fallback; } }
  function bridge(){ try { if(window.OKITHAKI_ANDROID)return window.OKITHAKI_ANDROID; }catch(e){} try{if(window.AndroidBridge)return window.AndroidBridge}catch(e){} return null; }
  function notify(text, ms=5500){ try{if(window.toast)return window.toast(String(text),ms); if(window.ITH&&ITH.toast)return ITH.toast(String(text),ms);}catch(e){} console.log(text); }
  async function jsonFetch(path,opt={}){
    const r=await fetch(apiBase()+path,Object.assign({cache:'no-store',credentials:'same-origin'},opt));
    let d={}; try{d=await r.json()}catch(e){}
    if(!r.ok||d.ok===false){const detail=d&&d.detail;const m=typeof detail==='string'?detail:(detail&&detail.message)||d.message||d.reason||('HTTP '+r.status);throw new Error(String(m));}
    return d;
  }
  function normalizeMode(mode){ return [FULL,STANDARD,NONE].includes(String(mode))?String(mode):FULL; }
  function localMode(channel){ return normalizeMode(localStorage.getItem(modeKey(channel))||FULL); }
  function setLocalMode(channel,mode){ mode=normalizeMode(mode); localStorage.setItem(modeKey(channel),mode); modeCache.set(String(channel),{mode,at:Date.now()}); return mode; }
  async function getMode(channel,force=false){
    channel=String(channel||activeChannel()); if(!channel.startsWith('dm:')) return localStorage.getItem(sharedKeyName(channel))?STANDARD:NONE;
    const hit=modeCache.get(channel); if(!force&&hit&&Date.now()-hit.at<15000)return hit.mode;
    let mode=localMode(channel);
    try{
      const d=await jsonFetch('/api/communication/security_mode_v249396?room_id='+encodeURIComponent(room())+'&channel='+encodeURIComponent(channel)+'&viewer_id='+encodeURIComponent(device())+'&_v='+Date.now());
      mode=normalizeMode(d.mode); setLocalMode(channel,mode);
    }catch(e){}
    return mode;
  }
  async function setMode(channel,mode,plaintextAck=false){
    channel=String(channel||activeChannel()); mode=normalizeMode(mode);
    if(!channel.startsWith('dm:')){setLocalMode(channel,mode);return{ok:true,mode,local_only:true};}
    const d=await jsonFetch('/api/communication/security_mode_v249396',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({room_id:room(),channel,device_id:device(),mode,plaintext_ack:plaintextAck===true})});
    setLocalMode(channel,d.mode||mode);
    if(mode===NONE&&plaintextAck)localStorage.setItem(ackKey(channel),'1');
    if(mode!==NONE)localStorage.removeItem(ackKey(channel));
    updateConversationIndicators(true);
    return d;
  }
  function modeInfo(mode){ return MODES[normalizeMode(mode)]; }
  function actualMessageMode(message){
    if(String(message&&message.iv||'')==='v249389:rsa-oaep-aes-gcm')return FULL;
    if(message&&message.is_encrypted)return STANDARD;
    return NONE;
  }
  function b64url(bytes){let s='';for(const b of bytes)s+=String.fromCharCode(b);return btoa(s).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,'');}
  function generateSharedKey(){const a=new Uint8Array(32);crypto.getRandomValues(a);return b64url(a);}
  async function standardEncrypt(text,channel){
    const pass=localStorage.getItem(sharedKeyName(channel));
    if(!pass||pass.length<12)throw new Error('Βάλε ισχυρό κοινό κωδικό τουλάχιστον 12 χαρακτήρων και στις δύο συσκευές.');
    if(window.e2eEncryptText){const out=await window.e2eEncryptText(String(text||''),channel);if(out)return out;}
    if(!crypto||!crypto.subtle)throw new Error('Η WebCrypto AES-GCM δεν είναι διαθέσιμη σε αυτή τη συσκευή.');
    const enc=new TextEncoder();const digest=await crypto.subtle.digest('SHA-256',enc.encode(pass));const key=await crypto.subtle.importKey('raw',digest,{name:'AES-GCM'},false,['encrypt']);const iv=crypto.getRandomValues(new Uint8Array(12));const cipher=await crypto.subtle.encrypt({name:'AES-GCM',iv},key,enc.encode(String(text||'')));const b64=x=>btoa(String.fromCharCode(...new Uint8Array(x)));return{iv:b64(iv),cipher_text:b64(cipher)};
  }
  function messageType(payload){try{const p=JSON.parse(String(payload||''));const k=String(p&&p.media&&p.media.kind||'').toLowerCase();if(['photo','image'].includes(k))return'photo';if(k==='video')return'video';if(['audio','voice'].includes(k))return'audio';if(['file','document'].includes(k))return'file';}catch(e){}return'message';}
  async function sendByMode(channel,payload){
    channel=String(channel||''); const peer=peerFromChannel(channel); if(!peer)throw new Error('Δεν είναι προσωπική συνομιλία.');
    const mode=await getMode(channel,true);
    if(mode===FULL){ if(!original||typeof original.sendMessage!=='function')throw new Error('Η πλήρης κρυπτογράφηση δεν φορτώθηκε.'); return original.sendMessage(channel,payload); }
    const base={room_id:room(),channel,sender_id:device(),recipient_id:peer,nickname:nickname(),security_mode:mode,message_type:messageType(payload),auto_delete_seconds:Number((await safeLoadSettings()).auto_delete_seconds||86400),storage_mode:String((await safeLoadSettings()).storage_mode||'encrypted_queue')};
    if(mode===STANDARD){const enc=await standardEncrypt(payload,channel);return jsonFetch('/api/communication/messages/send_v249396',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({...base,text:'',is_encrypted:true,iv:enc.iv,cipher_text:enc.cipher_text})});}
    if(localStorage.getItem(ackKey(channel))!=='1')throw new Error('Η λειτουργία χωρίς κρυπτογράφηση χρειάζεται ρητή επιβεβαίωση από την κλειδαριά της συνομιλίας.');
    return jsonFetch('/api/communication/messages/send_v249396',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({...base,text:String(payload||''),is_encrypted:false,iv:'',cipher_text:'',plaintext_ack:true})});
  }
  async function safeLoadSettings(){try{return original&&original.loadSettings?await original.loadSettings():{}}catch(e){return{auto_delete_seconds:86400,storage_mode:'encrypted_queue',screenshot_block:true,recording_block:true}}}
  function messagesPath(channel,since,limit=300){return'/api/communication/messages_v249396?room_id='+encodeURIComponent(room())+'&channel='+encodeURIComponent(channel)+'&viewer_id='+encodeURIComponent(device())+'&since='+encodeURIComponent(Number(since||0))+'&limit='+encodeURIComponent(limit);}
  async function markRead(message){
    if(!message||String(message.sender_id||'')===device())return null;
    try{return await jsonFetch('/api/communication/messages/read_v249396',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({room_id:room(),channel:String(message.channel||activeChannel()),message_id:String(message.message_id||''),reader_id:device()})});}catch(e){return null;}
  }
  function scheduleExpiry(message,element,meta){
    const expires=Number(meta&&meta.expires_at||message&&message.security_meta&&message.security_meta.expires_at||0); if(!expires||!element)return;
    const remove=()=>{try{element.remove()}catch(e){}}; const delay=Math.max(0,expires*1000-Date.now()); if(delay<=0)return remove(); setTimeout(remove,Math.min(delay,2147483647));
    const m=element.querySelector('.meta');if(m&&!m.querySelector('.ithExpiry396')){const s=document.createElement('small');s.className='ithExpiry396';s.textContent=' · διαγραφή '+new Date(expires*1000).toLocaleTimeString('el-GR',{hour:'2-digit',minute:'2-digit',second:'2-digit'});m.appendChild(s);}
  }
  async function onRendered(message,element){
    try{if(original&&original.onMessageRendered)await original.onMessageRendered(message,element)}catch(e){}
    if(!message||!element)return;
    const mode=actualMessageMode(message),info=modeInfo(mode),meta=element.querySelector('.meta');
    if(meta&&!meta.querySelector('.ithMsgSecurity396')){const b=document.createElement('span');b.className='ithMsgSecurity396 '+info.tone;b.textContent=info.icon+' '+info.short;meta.prepend(b);}
    element.setAttribute('data-security-mode-v249396',mode);
    if(String(message.sender_id||'')!==device()){const r=await markRead(message);scheduleExpiry(message,element,r||message.security_meta||message.secure_meta||{});}else scheduleExpiry(message,element,message.security_meta||message.secure_meta||{});
  }
  function modeCard(mode,current){const i=modeInfo(mode);return `<button type="button" class="ithModeCard396 ${i.tone} ${current===mode?'selected':''}" data-mode-v249396="${mode}"><span class="icon">${i.icon}</span><span><b>${esc(i.title)}</b><small>${esc(i.detail)}</small></span><span class="radio">${current===mode?'●':'○'}</span></button>`;}
  function closeMenu(){const menu=$('memberMenu');if(menu)menu.classList.remove('show');try{if(window.ITH&&ITH.refreshScrollableFormsV249392)ITH.refreshScrollableFormsV249392()}catch(e){}}
  async function openPanel(channel){
    if(panelBusy)return false; panelBusy=true;
    try{
      channel=String(channel||activeChannel());if(!channel.startsWith('dm:')){notify('Οι τρεις επαγγελματικές λειτουργίες κρυπτογράφησης εφαρμόζονται σε προσωπική συνομιλία φίλου.');return false;}
      const menu=$('memberMenu');if(!menu)return false;menu.classList.add('show');menu.innerHTML='<div class="ithSecurityPanel396"><div class="ithSecurityHead396"><button type="button" data-close396>‹</button><div><b>Κλειδαριά συνομιλίας</b><small>Επιλογή πραγματικού τρόπου προστασίας</small></div><button type="button" data-close396>×</button></div><div class="ithLoading396">Έλεγχος ρυθμίσεων…</div></div>';menu.querySelectorAll('[data-close396]').forEach(b=>b.onclick=closeMenu);
      const [current,settings]=await Promise.all([getMode(channel,true),safeLoadSettings()]);
      let native={};try{native=original&&original.nativeStatus?original.nativeStatus():{}}catch(e){}
      const peer=peerFromChannel(channel);let peerKey=null;try{if(original&&original.registerDeviceKey)await original.registerDeviceKey();if(original&&original.peerFromChannel&&peer&&window.ITHAKI_SECURE_V249389&&typeof window.ITHAKI_SECURE_V249389.__peerKeyV249396==='function')peerKey=await window.ITHAKI_SECURE_V249389.__peerKeyV249396(peer)}catch(e){}
      const key=localStorage.getItem(sharedKeyName(channel))||'';
      menu.innerHTML=`<div class="ithSecurityPanel396"><div class="ithSecurityHead396"><button type="button" data-close396>‹</button><div><b>🔐 Επαγγελματική κλειδαριά</b><small>Προσωπική συνομιλία · ${esc(modeInfo(current).short)}</small></div><button type="button" data-close396>×</button></div>
      <div class="ithSecurityState396"><b>Τρέχουσα λειτουργία: ${modeInfo(current).icon} ${esc(modeInfo(current).title)}</b><span>${esc(modeInfo(current).detail)}</span><small>${native&&native.ok?'Android Keystore διαθέσιμο στη συσκευή.':'Η πλήρης E2EE απαιτεί το νέο Android APK και δημόσια κλειδιά και των δύο φίλων.'}</small></div>
      <div class="ithModeGrid396">${modeCard(FULL,current)}${modeCard(STANDARD,current)}${modeCard(NONE,current)}</div>
      <div id="ithStandardKeyBox396" class="ithModeOptions396" ${current===STANDARD?'':'hidden'}><label>Κοινός ισχυρός κωδικός AES-GCM<input id="ithStandardKey396" type="password" value="${esc(key)}" autocomplete="new-password" placeholder="Τουλάχιστον 12 χαρακτήρες"></label><div class="row"><button type="button" id="ithGenerateKey396" class="btn">🎲 Δημιουργία ισχυρού κωδικού</button><button type="button" id="ithCopyKey396" class="btn">📋 Αντιγραφή</button></div><small>Στείλε τον κωδικό στον φίλο από διαφορετικό ασφαλές κανάλι. Η ΙΘΑΚΗ δεν τον ανεβάζει στον server.</small></div>
      <div id="ithNoneBox396" class="ithModeOptions396 danger" ${current===NONE?'':'hidden'}><b>⚠️ Ο server θα μπορεί να διαβάσει το περιεχόμενο.</b><label class="row"><input id="ithNoneAck396" type="checkbox" ${localStorage.getItem(ackKey(channel))==='1'?'checked':''}><span>Καταλαβαίνω ότι αυτή η λειτουργία δεν είναι End-to-end.</span></label><label>Γράψε ΧΩΡΙΣ για επιβεβαίωση<input id="ithNoneWord396" autocomplete="off"></label></div>
      <div class="ithCommonSettings396"><label>Auto-Delete<select id="ithTtl396"><option value="1">1 δευτ. — πειραματικό</option><option value="10">10 δευτ.</option><option value="30">30 δευτ.</option><option value="60">1 λεπτό</option><option value="300">5 λεπτά</option><option value="3600">1 ώρα</option><option value="86400">24 ώρες</option><option value="259200">72 ώρες</option><option value="0">Απενεργοποιημένο</option></select></label><label>Αποθήκευση server<select id="ithStorage396"><option value="encrypted_queue">Προσωρινή ουρά μέχρι παράδοση/λήξη</option><option value="zero_online_only">Μηδενική αποθήκευση — μόνο online</option></select></label><label class="row"><input id="ithShot396" type="checkbox" ${settings.screenshot_block!==false?'checked':''}><span>Μπλοκάρισμα screenshot</span></label><label class="row"><input id="ithRecord396" type="checkbox" ${settings.recording_block!==false?'checked':''}><span>Μπλοκάρισμα καταγραφής οθόνης</span></label></div>
      <div class="ithSecurityTruth396"><b>Ακριβής ένδειξη</b><span>Η οθόνη της συνομιλίας και κάθε μήνυμα δείχνουν τον πραγματικό τρόπο προστασίας. Η επιλογή «Χωρίς κρυπτογράφηση» δεν παρουσιάζεται ποτέ ως ασφαλής.</span></div>
      <button type="button" id="ithSaveSecurity396" class="btn green ithSaveSecurity396">Αποθήκευση και επιστροφή στη συνομιλία</button><div id="ithSecurityResult396" class="date"></div></div>`;
      menu.querySelectorAll('[data-close396]').forEach(b=>b.onclick=closeMenu);
      $('ithTtl396').value=String(Number(settings.auto_delete_seconds||86400));$('ithStorage396').value=String(settings.storage_mode||'encrypted_queue');
      let selected=current;
      const paint=()=>{menu.querySelectorAll('[data-mode-v249396]').forEach(x=>{const m=x.getAttribute('data-mode-v249396');x.classList.toggle('selected',m===selected);x.querySelector('.radio').textContent=m===selected?'●':'○';});$('ithStandardKeyBox396').hidden=selected!==STANDARD;$('ithNoneBox396').hidden=selected!==NONE;};
      menu.querySelectorAll('[data-mode-v249396]').forEach(x=>x.onclick=()=>{selected=normalizeMode(x.getAttribute('data-mode-v249396'));paint();});
      $('ithGenerateKey396').onclick=()=>{$('ithStandardKey396').value=generateSharedKey();};
      $('ithCopyKey396').onclick=async()=>{const v=$('ithStandardKey396').value;try{await navigator.clipboard.writeText(v);notify('Ο κοινός κωδικός αντιγράφηκε.')}catch(e){notify('Δεν έγινε αντιγραφή.')}};
      $('ithSaveSecurity396').onclick=async()=>{const result=$('ithSecurityResult396'),btn=$('ithSaveSecurity396');btn.disabled=true;result.textContent='Αποθήκευση…';try{
        if(selected===STANDARD){const v=$('ithStandardKey396').value.trim();if(v.length<12)throw new Error('Ο κοινός κωδικός πρέπει να έχει τουλάχιστον 12 χαρακτήρες.');localStorage.setItem(sharedKeyName(channel),v);}
        if(selected===NONE){if(!$('ithNoneAck396').checked||$('ithNoneWord396').value.trim().toUpperCase()!=='ΧΩΡΙΣ')throw new Error('Χρειάζεται το checkbox και η λέξη ΧΩΡΙΣ.');}
        if(original&&original.saveSettings)await original.saveSettings({auto_delete_seconds:Number($('ithTtl396').value),storage_mode:$('ithStorage396').value,screenshot_block:$('ithShot396').checked,recording_block:$('ithRecord396').checked,voice_mask_mode:'none'});
        await setMode(channel,selected,selected===NONE);
        result.textContent='Αποθηκεύτηκε. Επιστροφή στη συνομιλία…';await sleep(350);closeMenu();updateConversationIndicators(true);
      }catch(e){result.textContent='Δεν αποθηκεύτηκε: '+String(e.message||e);btn.disabled=false;}};
      try{if(window.ITH&&ITH.refreshScrollableFormsV249392)ITH.refreshScrollableFormsV249392()}catch(e){}
      return false;
    } finally { panelBusy=false; }
  }
  function badgeHtml(mode,prefix='Προσωπική συνομιλία'){const i=modeInfo(mode);return `${i.icon} ${prefix} · ${i.short}`;}
  async function updateDmBadge(force=false){
    const ch=activeChannel();if(!ch.startsWith('dm:'))return;
    if(!force&&ch===lastChannel&&document.querySelector('[data-conversation-mode-v249396]'))return;lastChannel=ch;
    const mode=await getMode(ch,force);const info=modeInfo(mode);const head=document.querySelector('#dmChatScreen .chatHead');if(!head)return;
    let b=head.querySelector('[data-conversation-mode-v249396]');if(!b){b=document.createElement('button');b.type='button';b.setAttribute('data-conversation-mode-v249396','1');b.className='ithConversationMode396';const title=head.querySelector('.chatTitle');if(title&&title.parentNode)title.parentNode.insertBefore(b,title.nextSibling);else head.appendChild(b);}b.className='ithConversationMode396 '+info.tone;b.textContent=badgeHtml(mode);b.title=info.detail;b.onclick=()=>openPanel(ch);
    document.documentElement.setAttribute('data-ithaki-dm-security-mode',mode);
  }
  function updateSpaceBadge(){
    const s=appState(),ch=String(s.currentSpaceChannel||'');if(!ch)return;const head=document.querySelector('#spacesPage .spaceHead,#spacesPage .chatHead,#spacesPage h2');if(!head)return;let b=document.querySelector('[data-space-mode-v249396]');if(!b){b=document.createElement('span');b.setAttribute('data-space-mode-v249396','1');b.className='ithSpaceMode396';head.appendChild(b);}b.textContent=localStorage.getItem(sharedKeyName(ch))?'🔒 Ομαδική συνομιλία · AES-GCM κοινό κλειδί':'💬 Ομαδική συνομιλία · χωρίς E2EE';
  }
  function updateCallBadge(){
    const box=document.querySelector('.callBox,#callBox,.callOverlay');if(!box)return;let b=box.querySelector('[data-call-security-v249396]');if(!b){b=document.createElement('div');b.setAttribute('data-call-security-v249396','1');b.className='ithCallSecurity396';box.prepend(b);}const s=appState(),type=String(s.call&&s.call.type||'').toLowerCase();b.textContent=(type==='voice'?'🎙️ Φωνητική κλήση':'📹 Βιντεοκλήση')+' · WebRTC DTLS-SRTP';b.title='Η μεταφορά WebRTC είναι κρυπτογραφημένη. Αυτό δεν σημαίνει ότι η λειτουργία Voice Mask είναι ενεργή.';
  }
  function updateConversationIndicators(force=false){updateDmBadge(force).catch(()=>{});updateSpaceBadge();updateCallBadge();}
  function torStatus(){try{const b=bridge();if(b&&typeof b.torStatusV249396==='function')return parseJson(b.torStatusV249396(),{});}catch(e){}return{ok:true,native_proxy_active:false,code_scaffold_ready:true,external_orbot_detected:false};}
  function openTorPanel(){
    const menu=$('memberMenu');if(!menu)return false;const st=torStatus();menu.innerHTML=`<div class="ithTorPanel396"><div class="ithSecurityHead396"><button type="button" data-close396>‹</button><div><b>🧅 Ιδιωτική σύνδεση μέσω Tor</b><small>Onion routing · επαγγελματική ενημέρωση</small></div><button type="button" data-close396>×</button></div><div class="ithTorHero396"><b>Περισσότερη ιδιωτικότητα χωρίς άμεση έκθεση της IP σου στον προορισμό</b><span>Το Tor είναι ένα δίκτυο ανωνυμίας που χρησιμοποιεί onion routing.</span></div><div class="ithTorTruth396"><b>Σημαντικό</b><span>Η λειτουργία Tor δεν είναι ακόμη ενεργή μέσα στην ΙΘΑΚΗ. Το Tor μειώνει την έκθεση της IP, αλλά δεν εγγυάται ότι «κανείς δεν ξέρει ποιος είσαι». Λογαριασμοί, περιεχόμενο, συσκευή ή λάθη χρήσης μπορούν να αποκαλύψουν ταυτότητα.</span></div><div class="ithTorStatus396"><span>Native proxy routing</span><b>${st.native_proxy_active?'Ενεργό':'Δεν είναι ενεργό'}</b><span>Κώδικας ενσωμάτωσης</span><b>${st.code_scaffold_ready?'Προετοιμασμένος':'Δεν βρέθηκε'}</b><span>Εξωτερικό Orbot</span><b>${st.external_orbot_detected?'Βρέθηκε':'Δεν βρέθηκε/δεν ελέγχθηκε'}</b></div><button type="button" class="btn" id="ithTorFuture396">Κώδικας Tor — μελλοντική ενεργοποίηση</button><div id="ithTorResult396" class="date">Το κουμπί υπάρχει για επαγγελματική ενημέρωση και μελλοντική native ενσωμάτωση. Δεν αλλάζει σήμερα τη σύνδεση.</div></div>`;menu.classList.add('show');menu.querySelectorAll('[data-close396]').forEach(b=>b.onclick=closeMenu);$('ithTorFuture396').onclick=()=>{const r=$('ithTorResult396');r.textContent='Δεν ενεργοποιήθηκε proxy. Απαιτείται δοκιμασμένη native δρομολόγηση όλων των HTTP/WebSocket/WebRTC ροών.';};try{if(window.ITH&&ITH.refreshScrollableFormsV249392)ITH.refreshScrollableFormsV249392()}catch(e){}return false;
  }
  function injectProfileButton(){
    const page=$('profilePage');if(!page||page.querySelector('[data-tor-profile-v249396]'))return;const wrap=page.querySelector('.profileCleanWrap')||page.firstElementChild;if(!wrap)return;const section=document.createElement('section');section.className='card profilePanelClean ithTorProfileCard396';section.setAttribute('data-tor-profile-v249396','1');section.innerHTML=`<button type="button" class="ithTorProfileButton396"><span class="torIcon">🧅</span><span><b>Ιδιωτική σύνδεση Tor</b><small>Onion routing · Μειώνει την έκθεση της IP · Σχεδιαζόμενη λειτουργία</small></span><span class="status">Κώδικας έτοιμος<br>όχι ενεργό</span></button>`;const hero=wrap.querySelector('.profileHeroClean');if(hero&&hero.parentNode)hero.parentNode.insertBefore(section,hero.nextSibling);else wrap.prepend(section);section.querySelector('button').onclick=openTorPanel;
  }
  function injectCss(){if($('ithProfessionalSecurityCss396'))return;const st=document.createElement('style');st.id='ithProfessionalSecurityCss396';st.textContent=`
  .ithConversationMode396{grid-column:1/-1;justify-self:start;display:inline-flex;align-items:center;min-height:30px;border-radius:999px;padding:5px 10px;border:1px solid;font-size:11px;font-weight:1000;letter-spacing:.1px;white-space:normal;text-align:left}.ithConversationMode396.full{color:#b9f8d4;background:rgba(24,127,82,.2);border-color:rgba(91,239,166,.48)}.ithConversationMode396.standard{color:#dcecff;background:rgba(38,91,159,.22);border-color:rgba(105,174,255,.45)}.ithConversationMode396.none{color:#ffd3c6;background:rgba(158,47,25,.23);border-color:rgba(255,112,82,.5)}
  .ithMsgSecurity396{display:inline-flex;margin-right:6px;padding:2px 6px;border-radius:999px;font-size:9px;font-weight:1000}.ithMsgSecurity396.full{color:#8cf0b8;background:rgba(29,125,80,.22)}.ithMsgSecurity396.standard{color:#b8d9ff;background:rgba(35,91,160,.22)}.ithMsgSecurity396.none{color:#ffc1b0;background:rgba(160,44,25,.24)}.ithExpiry396{color:#f0c86e}
  .ithSecurityPanel396,.ithTorPanel396{display:grid;gap:12px;max-height:min(88vh,850px);overflow:auto;padding:2px 2px 18px}.ithSecurityHead396{position:sticky;top:0;z-index:3;display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:10px;align-items:center;padding:10px;border-radius:16px;background:rgba(3,12,20,.96);border:1px solid rgba(255,215,112,.2)}.ithSecurityHead396 button{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}.ithSecurityHead396 div{display:grid;gap:2px}.ithSecurityHead396 b{color:#ffe09a}.ithSecurityHead396 small{color:rgba(255,255,255,.65)}
  .ithSecurityState396,.ithSecurityTruth396,.ithTorTruth396,.ithTorHero396{display:grid;gap:6px;border-radius:17px;padding:13px;border:1px solid rgba(255,219,123,.22);background:rgba(255,255,255,.05)}.ithSecurityState396 span,.ithSecurityTruth396 span,.ithTorTruth396 span,.ithTorHero396 span{font-size:12px;line-height:1.5;color:rgba(255,255,255,.76)}
  .ithModeGrid396{display:grid;gap:9px}.ithModeCard396{width:100%;display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:10px;align-items:center;text-align:left;border-radius:18px;padding:12px;border:1px solid rgba(255,255,255,.14);background:rgba(255,255,255,.045);color:#fff}.ithModeCard396 .icon{font-size:25px}.ithModeCard396 span:nth-child(2){display:grid;gap:4px}.ithModeCard396 small{font-size:11px;line-height:1.4;color:rgba(255,255,255,.67)}.ithModeCard396 .radio{font-size:20px}.ithModeCard396.selected.full{border-color:#58e9a2;background:rgba(20,128,80,.19)}.ithModeCard396.selected.standard{border-color:#70b4ff;background:rgba(31,93,165,.2)}.ithModeCard396.selected.none{border-color:#ff7659;background:rgba(155,42,23,.22)}
  .ithModeOptions396,.ithCommonSettings396{display:grid;gap:9px;border-radius:17px;padding:12px;border:1px solid rgba(255,255,255,.13);background:rgba(255,255,255,.04)}.ithModeOptions396[hidden]{display:none!important}.ithModeOptions396.danger{border-color:rgba(255,105,75,.45);background:rgba(155,38,20,.17)}.ithSecurityPanel396 label{display:grid;gap:5px;font-weight:900}.ithSecurityPanel396 input,.ithSecurityPanel396 select{width:100%;min-height:44px;border-radius:13px;border:1px solid rgba(255,222,135,.25);background:#07111b;color:#fff;padding:8px 10px}.ithSecurityPanel396 label.row{display:flex;align-items:center}.ithSecurityPanel396 label.row input{width:22px;min-height:22px}.ithSaveSecurity396{width:100%;min-height:50px}.ithLoading396{padding:20px;text-align:center}
  .ithSpaceMode396,.ithCallSecurity396{display:inline-flex;margin:6px;padding:5px 9px;border-radius:999px;border:1px solid rgba(130,195,255,.35);background:rgba(26,76,130,.2);color:#d8ebff;font-size:10px;font-weight:900}.ithCallSecurity396{position:relative;z-index:5;align-self:center}
  .ithTorProfileCard396{padding:8px!important}.ithTorProfileButton396{width:100%;display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:12px;align-items:center;text-align:left;border:1px solid rgba(188,137,255,.4);background:linear-gradient(135deg,rgba(63,30,96,.35),rgba(8,20,34,.8));color:#fff;border-radius:20px;padding:13px}.ithTorProfileButton396 .torIcon{font-size:30px}.ithTorProfileButton396 span:nth-child(2){display:grid;gap:4px}.ithTorProfileButton396 small{color:rgba(255,255,255,.7);line-height:1.35}.ithTorProfileButton396 .status{text-align:right;font-size:10px;color:#e8c7ff;font-weight:900}.ithTorHero396{border-color:rgba(187,130,255,.42);background:linear-gradient(135deg,rgba(87,36,132,.24),rgba(255,255,255,.035))}.ithTorStatus396{display:grid;grid-template-columns:1fr auto;gap:8px;padding:12px;border-radius:16px;background:rgba(255,255,255,.045)}.ithTorStatus396 b{color:#ffe09a;text-align:right}
  @media(max-width:620px){.ithConversationMode396{font-size:10px}.ithTorProfileButton396{grid-template-columns:auto 1fr}.ithTorProfileButton396 .status{grid-column:1/-1;text-align:left;padding-left:44px}.ithSecurityPanel396,.ithTorPanel396{max-height:86vh}}
  `;document.head.appendChild(st);}
  function patchSecureApi(){
    const sec=window.ITHAKI_SECURE_V249389;if(!sec||sec.__v249396Patched)return false;
    original={sendMessage:sec.sendMessage,openPanel:sec.openPanel,onMessageRendered:sec.onMessageRendered,messagesPath:sec.messagesPath,loadSettings:sec.loadSettings,saveSettings:sec.saveSettings,nativeStatus:sec.nativeStatus,registerDeviceKey:sec.registerDeviceKey,applySecureScreen:sec.applySecureScreen,peerFromChannel:sec.peerFromChannel};
    sec.sendMessage=sendByMode;sec.openPanel=openPanel;sec.messagesPath=messagesPath;sec.onMessageRendered=onRendered;sec.getConversationModeV249396=getMode;sec.setConversationModeV249396=setMode;sec.updateConversationIndicatorsV249396=updateConversationIndicators;sec.__v249396Patched=true;
    return true;
  }
  function install(){injectCss();patchSecureApi();injectProfileButton();updateConversationIndicators(true);window.ITH=window.ITH||{};Object.assign(window.ITH,{openProfessionalSecurityV249396:openPanel,openTorPrivacyV249396:openTorPanel,getConversationModeV249396:getMode,setConversationModeV249396:setMode,refreshConversationTypeV249396:()=>updateConversationIndicators(true)});document.documentElement.setAttribute('data-ithaki-professional-security','V249396');document.documentElement.setAttribute('data-ithaki-tor-status','code-ready-not-active');
    const ob=new MutationObserver(()=>{patchSecureApi();injectProfileButton();updateConversationIndicators(false)});ob.observe(document.documentElement,{subtree:true,childList:true,attributes:true,attributeFilter:['class','style','data-page']});setInterval(()=>{patchSecureApi();injectProfileButton();updateConversationIndicators(false)},850);
  }
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',install,{once:true});else install();
})();
