/* OK ITHAKI V249398 — direct preview publication and universal conversation security/anonymity menu.
 * Personal chats retain the V249396 three-mode panel.
 * Multi-member groups, rooms and communities use real shared-key AES-GCM or explicit plaintext.
 * "Anonymous" here hides the displayed member name inside that conversation; it does not hide IP/network identity.
 */
(function(){
  'use strict';
  /* V249412_PUBLISH_OBSERVER_STABLE */
  if(window.__ITHAKI_V249398_PUBLISH_SCOPE_SECURITY__)return;
  window.__ITHAKI_V249398_PUBLISH_SCOPE_SECURITY__=1;

  const VERSION='V249413-security-anonymity-no-professional-preview';
  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));
  const wrapped=new Map();
  let panelBusy=false;

  function st(){try{return window.state||state||{}}catch(e){return window.state||{}}}
  function room(){const s=st();return String(s.room||localStorage.getItem('ith_room')||'ithaki-phone-test')}
  function activeChannel(){const s=st();return String(s.currentSpaceChannel||s.activeChannel||'')}
  function scope(channel){channel=String(channel||'');if(channel.startsWith('dm:'))return'dm';if(channel.startsWith('group:'))return'group';if(channel.startsWith('space:'))return'space';if(channel.startsWith('community:'))return'community';return'channel'}
  function scopeTitle(channel){const k=scope(channel);if(k==='dm')return'Προσωπική συνομιλία';if(k==='group')return'Ομαδική συνομιλία';if(k==='space')return'Δωμάτιο / κοινότητα';if(k==='community')return'Κοινότητα';return'Συνομιλία'}
  function keyName(channel){return'ith_e2e_key_'+String(channel||'main')}
  function modeName(channel){return'ith_scope_security_mode_v249398:'+room()+':'+String(channel||'')}
  function identityName(channel){return'ith_scope_identity_v249398:'+room()+':'+String(channel||'')}
  function mode(channel){return localStorage.getItem(modeName(channel))||(localStorage.getItem(keyName(channel))?'standard_aes':'no_encryption')}
  function identity(channel){return localStorage.getItem(identityName(channel))==='anonymous'?'anonymous':'profile'}
  function notify(text,ms=6500){try{if(typeof window.toast==='function')return window.toast(String(text),ms);if(window.ITH&&typeof ITH.notifyAppEvent==='function')return ITH.notifyAppEvent(String(text))}catch(e){}console.log(text)}
  function closeMenu(){const m=$('memberMenu');if(m)m.classList.remove('show');return false}
  function fileKind(file){const t=String(file&&file.type||'').toLowerCase(),n=String(file&&file.name||'').toLowerCase();if(t.startsWith('video/')||/\.(mp4|mov|m4v|webm|3gp|avi|mkv)$/.test(n))return'video';if(t.startsWith('image/')||/\.(jpg|jpeg|png|webp|gif|heic)$/.test(n))return'photo';if(t.startsWith('audio/'))return'audio';return'file'}
  function channelFor(peer){const s=st();return'dm:'+[(s.device||localStorage.getItem('ith_device')||''),String(peer||'')].sort().join(':')}
  function generateKey(){const a=new Uint8Array(32);crypto.getRandomValues(a);let x='';for(const b of a)x+=String.fromCharCode(b);return btoa(x).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,'')}

  function injectCss(){if($('ithV249398Css'))return;const e=document.createElement('style');e.id='ithV249398Css';e.textContent=`
  .ithScopeSecurity398{display:flex;align-items:center;gap:7px;flex-wrap:wrap;margin:5px 8px;padding:7px 9px;border:1px solid rgba(102,190,255,.35);border-radius:15px;background:linear-gradient(135deg,rgba(26,82,139,.22),rgba(4,15,25,.92));color:#e9f5ff;font-size:11px;font-weight:900}.ithScopeSecurity398 button{border:0;background:transparent;color:inherit;padding:2px;font:inherit;text-align:left}.ithScopeSecurity398 .anon{margin-left:auto;color:#ffe09a;font-size:10px}
  .ithScopePanel398{display:grid;gap:11px;max-height:min(88vh,860px);overflow:auto;padding:2px 2px 18px}.ithScopeHead398{position:sticky;top:0;z-index:4;display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:9px;align-items:center;padding:9px;border-radius:16px;background:rgba(3,12,20,.97);border:1px solid rgba(255,215,112,.22)}.ithScopeHead398 button{width:42px;height:42px;border-radius:13px;border:1px solid rgba(255,255,255,.15);background:rgba(255,255,255,.07);color:#fff;font-size:22px}.ithScopeHead398 small{display:block;color:rgba(255,255,255,.65);margin-top:3px}.ithScopeCard398{padding:12px;border-radius:17px;border:1px solid rgba(255,255,255,.13);background:rgba(255,255,255,.045);display:grid;gap:8px}.ithScopeChoice398{width:100%;display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:10px;align-items:center;text-align:left;padding:11px;border-radius:16px;border:1px solid rgba(255,255,255,.14);background:rgba(255,255,255,.04);color:#fff}.ithScopeChoice398.selected{border-color:#66b8ff;background:rgba(41,103,171,.2)}.ithScopeChoice398.disabled{opacity:.58}.ithScopeChoice398 small{display:block;color:rgba(255,255,255,.65);line-height:1.35;margin-top:3px}.ithScopePanel398 input{width:100%;min-height:44px;border-radius:13px;border:1px solid rgba(255,220,130,.28);background:#07131f;color:#fff;padding:9px}.ithScopeActions398{display:flex;gap:7px;flex-wrap:wrap}.ithScopeActions398 button{min-height:42px}.ithScopeWarning398{color:#ffd0c4;border-color:rgba(255,107,76,.42);background:rgba(148,36,18,.18)}
  #ithPublicationWorkspace387.ithDirectPreviewPending398{pointer-events:none;opacity:.72}#previewModal.ithDirectPreview398{z-index:2147483647!important}
  `;document.head.appendChild(e)}

  function currentPublishDestination(){const s=st();if(s.page==='dm'&&s.activeChannel){const ch=String(s.activeChannel);return{ctx:ch.startsWith('dm:')?'dm':'space',target:ch}}if(s.page==='spaces'&&s.currentSpaceChannel)return{ctx:'space',target:String(s.currentSpaceChannel)};return{ctx:'feed',target:''}}
  function directChoose(action){const d=currentPublishDestination();const I=window.ITH||{};if(action==='camera_photo'&&typeof I.captureMedia==='function')return I.captureMedia(d.ctx,'photo',d.target);if(action==='camera_video'&&typeof I.captureMedia==='function')return I.captureMedia(d.ctx,'video',d.target);if(action==='audio'&&typeof I.startAudioRecording==='function')return I.startAudioRecording(d.ctx,d.target);const kind=action==='gallery_photo'?'photo':action==='gallery_video'?'video':'file';if(typeof I.chooseFile==='function')return I.chooseFile(d.ctx,kind,d.target);notify('Η επιλογή αρχείου δεν φορτώθηκε.');return false}
  function capturePlus(ev){const b=ev.target&&ev.target.closest?ev.target.closest('#plusSheet [data-act]'):null;if(!b)return;const a=String(b.dataset.act||'');if(!['camera_photo','camera_video','audio','gallery_photo','gallery_video','file'].includes(a))return;ev.preventDefault();ev.stopPropagation();ev.stopImmediatePropagation();$('plusSheet')?.classList.remove('show');directChoose(a)}
  function captureHomePublish(ev){const b=ev.target&&ev.target.closest?ev.target.closest('#homePage .tile'):null;if(!b||!/Δημοσίευση|Post/i.test(b.textContent||''))return;ev.preventDefault();ev.stopPropagation();ev.stopImmediatePropagation();const I=window.ITH||{};document.getElementById('plusSheet')?.classList.remove('show');document.documentElement.setAttribute('data-ithaki-home-publish-route-v249412','create');if(typeof I.page==='function')return I.page('create');if(typeof window.page==='function')return window.page('create');notify('Δεν άνοιξε η οθόνη δημοσίευσης.');return false;}

  function directWorkspacePreview(){try{window.ITH&&ITH.page&&ITH.page('create')}catch(e){}notify('Η δημοσίευση γίνεται μόνο από το + της ΙΘΑΚΗΣ.');return false}
  function bindWorkspaceDirect(){['ithPublicationWorkspace387','ithPreviewDestination387','ithPublicationTool388','ithPublicationTool387'].forEach(id=>$(id)?.remove());return false}

  function securitySummary(channel){if(scope(channel)==='dm')return'🔐 Προσωπική συνομιλία · πλήρης επιλογή ασφάλειας';const encrypted=!!localStorage.getItem(keyName(channel));return(encrypted?'🔒 AES-GCM κοινό κλειδί':'⚠️ Χωρίς κρυπτογράφηση')+' · '+(identity(channel)==='anonymous'?'Ανώνυμη εμφάνιση':'Με προφίλ')}
  function openScopePanel(channel){channel=String(channel||activeChannel());if(!channel){notify('Άνοιξε πρώτα συνομιλία, ομάδα, δωμάτιο ή κοινότητα.');return false}if(channel.startsWith('dm:')){try{if(window.ITH&&typeof ITH.openProfessionalSecurityV249396==='function')return ITH.openProfessionalSecurityV249396(channel)}catch(e){}notify('Η προσωπική κλειδαριά δεν φορτώθηκε.');return false}if(panelBusy)return false;panelBusy=true;try{const menu=$('memberMenu');if(!menu)return false;let selected=mode(channel)==='standard_aes'?'standard_aes':'no_encryption',who=identity(channel),key=localStorage.getItem(keyName(channel))||'';menu.innerHTML=`<div class="ithScopePanel398"><div class="ithScopeHead398"><button type="button" data-close398>‹</button><div><b>🔐 Ασφάλεια και ανωνυμία</b><small>${esc(scopeTitle(channel))}</small></div><button type="button" data-close398>×</button></div><div class="ithScopeCard398"><b>Τρόπος κρυπτογράφησης</b><button type="button" class="ithScopeChoice398 disabled"><span>🔐</span><span><b>Πλήρης E2EE πολλών μελών</b><small>Δεν δηλώνεται ενεργή. Χρειάζεται πραγματική διαχείριση κλειδιών ομάδας και αλλαγή κλειδιού όταν μπαίνει ή φεύγει μέλος.</small></span><span>—</span></button><button type="button" data-sec398="standard_aes" class="ithScopeChoice398 ${selected==='standard_aes'?'selected':''}"><span>🔒</span><span><b>AES-GCM κοινό κλειδί</b><small>Πραγματική κρυπτογράφηση περιεχομένου. Όλα τα μέλη χρειάζονται τον ίδιο ισχυρό κωδικό.</small></span><span>${selected==='standard_aes'?'●':'○'}</span></button><button type="button" data-sec398="no_encryption" class="ithScopeChoice398 ${selected==='no_encryption'?'selected':''}"><span>⚠️</span><span><b>Χωρίς κρυπτογράφηση περιεχομένου</b><small>Το κείμενο παραμένει αναγνώσιμο στον server. Η μεταφορά προστατεύεται μόνο από HTTPS.</small></span><span>${selected==='no_encryption'?'●':'○'}</span></button></div><div id="ithScopeKeyBox398" class="ithScopeCard398" ${selected==='standard_aes'?'':'hidden'}><label><b>Κοινός κωδικός AES-GCM</b><input id="ithScopeKey398" type="password" value="${esc(key)}" placeholder="Τουλάχιστον 12 χαρακτήρες"></label><div class="ithScopeActions398"><button id="ithGenerate398" class="btn" type="button">🎲 Δημιουργία</button><button id="ithCopy398" class="btn" type="button">📋 Αντιγραφή</button></div><small>Ο κωδικός μένει μόνο στη συσκευή. Μοιράσου τον από διαφορετικό ασφαλές κανάλι.</small></div><div id="ithScopePlain398" class="ithScopeCard398 ithScopeWarning398" ${selected==='no_encryption'?'':'hidden'}><b>⚠️ Επιβεβαίωση</b><span>Η επιλογή αυτή δεν είναι End-to-end και το περιεχόμενο μπορεί να διαβαστεί στον server.</span></div><div class="ithScopeCard398"><b>Εμφάνιση ταυτότητας μέσα στη συνομιλία</b><button type="button" data-id398="profile" class="ithScopeChoice398 ${who==='profile'?'selected':''}"><span>👤</span><span><b>Με προφίλ</b><small>Εμφανίζεται το όνομα του μέλους.</small></span><span>${who==='profile'?'●':'○'}</span></button><button type="button" data-id398="anonymous" class="ithScopeChoice398 ${who==='anonymous'?'selected':''}"><span>🕶️</span><span><b>Ανώνυμη εμφάνιση</b><small>Στα νέα μηνύματα εμφανίζεται «Ανώνυμος». Δεν κρύβει IP, συσκευή ή στοιχεία από τον server.</small></span><span>${who==='anonymous'?'●':'○'}</span></button></div><button id="ithSaveScope398" type="button" class="btn green">Αποθήκευση και επιστροφή</button><div id="ithScopeResult398" class="date"></div></div>`;menu.classList.add('show');menu.querySelectorAll('[data-close398]').forEach(x=>x.onclick=closeMenu);const paint=()=>{menu.querySelectorAll('[data-sec398]').forEach(x=>{const yes=x.dataset.sec398===selected;x.classList.toggle('selected',yes);x.lastElementChild.textContent=yes?'●':'○'});$('ithScopeKeyBox398').hidden=selected!=='standard_aes';$('ithScopePlain398').hidden=selected!=='no_encryption';menu.querySelectorAll('[data-id398]').forEach(x=>{const yes=x.dataset.id398===who;x.classList.toggle('selected',yes);x.lastElementChild.textContent=yes?'●':'○'})};menu.querySelectorAll('[data-sec398]').forEach(x=>x.onclick=()=>{selected=x.dataset.sec398;paint()});menu.querySelectorAll('[data-id398]').forEach(x=>x.onclick=()=>{who=x.dataset.id398;paint()});$('ithGenerate398').onclick=()=>{$('ithScopeKey398').value=generateKey()};$('ithCopy398').onclick=async()=>{try{await navigator.clipboard.writeText($('ithScopeKey398').value);notify('Ο κοινός κωδικός αντιγράφηκε.')}catch(e){notify('Δεν έγινε αντιγραφή.')}};$('ithSaveScope398').onclick=async()=>{const out=$('ithScopeResult398');try{if(selected==='standard_aes'){const v=$('ithScopeKey398').value.trim();if(v.length<12)throw new Error('Ο κοινός κωδικός πρέπει να έχει τουλάχιστον 12 χαρακτήρες.');localStorage.setItem(keyName(channel),v)}else localStorage.removeItem(keyName(channel));localStorage.setItem(modeName(channel),selected);localStorage.setItem(identityName(channel),who);out.textContent='Αποθηκεύτηκε.';updateBadges();await sleep(250);closeMenu()}catch(e){out.textContent='Δεν αποθηκεύτηκε: '+String(e.message||e)}};try{window.ITH&&ITH.refreshScrollableFormsV249392&&ITH.refreshScrollableFormsV249392()}catch(e){}return false}finally{panelBusy=false}}

  function ensureBadge(){const s=st();const ch=activeChannel();document.querySelectorAll('[data-scope-security-v249398]').forEach(x=>x.remove());if(!ch||ch.startsWith('dm:'))return;let host=null;if(s.page==='dm')host=document.querySelector('#dmChatScreen .chatHead')||$('dmChatScreen');else if(s.page==='spaces')host=document.querySelector('#spacesPage .spaceHead,#spacesPage .chatHead,#spacesPage .spaceChatHead')||$('spacesPage');if(!host)return;const bar=document.createElement('div');bar.className='ithScopeSecurity398';bar.setAttribute('data-scope-security-v249398','1');bar.innerHTML=`<button type="button">${esc(securitySummary(ch))} · Επιλογή</button><span class="anon">${identity(ch)==='anonymous'?'🕶️ Ανώνυμη εμφάνιση':'👤 Με προφίλ'}</span>`;bar.querySelector('button').onclick=()=>openScopePanel(ch);host.appendChild(bar)}
  function updateBadges(){ensureBadge();document.documentElement.setAttribute('data-ithaki-scope-security',VERSION)}

  async function withIdentity(channel,fn,thisArg,args){if(!channel||channel.startsWith('dm:')||identity(channel)!=='anonymous')return fn.apply(thisArg,args);const s=st(),old=s.name,oldNick=s.nickname;try{s.name='Ανώνυμος';s.nickname='Ανώνυμος';return await fn.apply(thisArg,args)}finally{s.name=old;s.nickname=oldNick}}
  function wrap(name,resolver,before){const I=window.ITH||{},current=I[name];if(typeof current!=='function'||current.__v249398Wrapper)return;const wrapper=async function(){const channel=String(resolver.apply(this,arguments)||'');if(before)before(channel);return withIdentity(channel,current,this,arguments)};wrapper.__v249398Wrapper=true;wrapper.__v249398Base=current;I[name]=wrapper;try{window[name]=wrapper}catch(e){}wrapped.set(name,wrapper)}
  function wrapSenders(){wrap('sendDMText',()=>String(st().activeChannel||''));wrap('sendSpaceText',()=>String(st().currentSpaceChannel||''));wrap('sendPreview',()=>{const p=st().preview||{},target=String(p.target||'');if(target.startsWith('group:')&&p.ctx==='dm')p.ctx='space';return target||String(st().currentSpaceChannel||st().activeChannel||'')})}

  function installExports(){window.ITH=window.ITH||{};ITH.openConversationSecurityV249398=openScopePanel;ITH.openE2EPanel=openScopePanel;ITH.openQuickPublishPreviewV249398=directWorkspacePreview;ITH.scopeSecurityVersionV249398=VERSION}
  let refreshTimer398=0;function scheduleRefresh398(){clearTimeout(refreshTimer398);refreshTimer398=setTimeout(()=>{installExports();bindWorkspaceDirect();wrapSenders();updateBadges()},140)}function install(){injectCss();installExports();document.addEventListener('click',capturePlus,true);document.addEventListener('click',captureHomePublish,true);bindWorkspaceDirect();wrapSenders();updateBadges();const host=document.body||document.documentElement;const ob=new MutationObserver(list=>{if(list.some(m=>m.type==='childList'&&(m.addedNodes.length||m.removedNodes.length)))scheduleRefresh398()});ob.observe(host,{childList:true,subtree:true});setInterval(()=>{installExports();bindWorkspaceDirect();wrapSenders();updateBadges()},5000);document.documentElement.setAttribute('data-ithaki-publish-routing','direct-create-v249412');document.documentElement.setAttribute('data-ithaki-publish-observer-v249412','childlist-debounced');document.documentElement.setAttribute('data-ithaki-security-scope','dm-group-space-community')}
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',install,{once:true});else install();
})();
