/* OK ITHAKI V249502 — one reliable escape/back owner for all real tabs and overlays.
 * Fixes: feed avatar falsely treated as an overlay, home menu auto-closing,
 * duplicate escape arrows, reusable roots becoming permanently hidden,
 * nested professional/creator tabs closing the whole center, and missing page back.
 */
(function(){
'use strict';
if(window.__ITHAKI_V249502_GLOBAL_ESCAPE__)return;
window.__ITHAKI_V249502_GLOBAL_ESCAPE__={singleOwner:true,allTabs:true,nestedBack:true,androidBack:true,avatarMenuBack:true,directMessageBack:true};
window.__ITHAKI_V249392_NAVIGATION_UI__=1;
const VERSION='V249502-avatar-menu-dm-back-truth';
const $=id=>document.getElementById(id);
const reusable=new Set(['previewModal','memberMenu','plusSheet']);
const overlaySelectors=[
 '#previewModal.show','#memberMenu.show','#plusSheet.show',
 '#ithAccountModal383','#ithUnifiedFriendGate391','#friendGuardModal380',
 '#commentsModal','#memberDetailModal','#memberModal','#groupModalV249282',
 '#translationBookModal324','#translationBookOverlay324','#ithBookModal332','#ithBookModal335','#ithBookModal337',
 '#ithLightModal339','#ithWallModal339','#ithCreatorPublic387','#ithCreatorQrModal387','#ithPublicationWorkspace387',
 '#ithSecurePanelV249389','#lighthouseOverlayV249278','#guideOverlayV249271','#guideOverlayV249272','#guideOverlayV249273','#guideOverlayV249275','#guideOverlayV249276','#guideOverlayV249282',
 '#bottleSeaOverlayV249274','#commOverlayV249280','#pigeonMeshPanelV249291','#socratakiPanelV249252',
 '#ithProCenterV249477','#ith477StoryViewer','#creatorAnalyticsPanel410','#ithUnifiedWall397','#ithV411Wall','#v411Overlay','#v411CommentLayer',
 '#ithShareOverlayV249433','#ithDiagPanelV249429','#ithCommentsSheetV249430','#ithPreviewStableModal400','#ithGroupCreatorV249431',
 '#callOverlay','.ith477Overlay','.ith477StoryViewer','.ithModal383','.ithCreator387','.modal:not([hidden])','.fullScreenViewer',
 '.notificationPanelPro','.proPollModal','.securePanelV249389','.lighthouseScreenV249278','.wallScreen339','.lightScreen339',
 '[role="dialog"][aria-modal="true"]'
];
const scrollBoxes=['.ithModalBox383','.ithUnifiedFriendBox391','.ithCreatorBox387','.modalBox','.previewBox','.memberDetailBox','.memberModalBox','.friendGuardBox380','.groupPanelV249282','.translationBookModalV249324','.bottleSeaPanelV249274','.commPanelV249280','.ith477Shell','.ca410Shell','.v411CommentSheet','.panelBody','.commentPanel','.callBox','.fileBox','.qrBox','.savedItemsBox','.spacePanelV249311'];
let currentPage='home', previousPage='home', updating=false;
function visible(el){if(!el||!el.isConnected||el.hidden)return false;const c=getComputedStyle(el);if(c.display==='none'||c.visibility==='hidden'||Number(c.opacity)===0||c.pointerEvents==='none')return false;const r=el.getBoundingClientRect();return r.width>2&&r.height>2}
function z(el){const n=parseInt(getComputedStyle(el).zIndex,10);return Number.isFinite(n)?n:0}
function actualOverlay(el){if(!visible(el))return false;if(el.matches('.feedAvatarOverlay,.homeMenu,.stableMainMenu,.page,.nav,.ith477StoryBar,.ith477StoryCircle'))return false;return overlaySelectors.some(s=>{try{return el.matches(s)}catch(e){return false}})}
function overlays(){const set=new Set();overlaySelectors.forEach(s=>{try{document.querySelectorAll(s).forEach(x=>{if(actualOverlay(x))set.add(x)})}catch(e){}});return [...set].sort((a,b)=>z(a)-z(b))}
function topOverlay(){const a=overlays();return a[a.length-1]||null}
function text(el){return String(el&&el.textContent||'').replace(/\s+/g,' ').trim()}
function nativeBack(el){const all=[...el.querySelectorAll('button,a')].filter(x=>visible(x)&&!x.classList.contains('ithEscape502')&&!x.classList.contains('ithEscape392'));
 const scored=all.map(x=>{let s=0,t=text(x),a=(x.getAttribute('aria-label')||'')+' '+(x.title||'')+' '+(x.id||'')+' '+(x.className||'');if(/^(‹|←|⬅|↩)$/.test(t))s+=100;if(/πίσω|επιστροφ|back|return/i.test(a))s+=80;if(/back/i.test(String(x.id)+' '+String(x.className)))s+=40;if(/^(×|✕|✖)$/.test(t))s-=60;return{x,s}}).filter(q=>q.s>0).sort((a,b)=>b.s-a.s);return scored[0]&&scored[0].x}
function nativeClose(el){const all=[...el.querySelectorAll('button,a')].filter(x=>visible(x)&&!x.classList.contains('ithEscape502')&&!x.classList.contains('ithEscape392'));return all.find(x=>/^(×|✕|✖)$/.test(text(x))||/κλείσιμο|έξοδος|close|exit/i.test((x.getAttribute('aria-label')||'')+' '+(x.title||'')+' '+(x.id||'')+' '+(x.className||'')))||null}
function safeClick(b){if(!b)return false;try{b.click();return true}catch(e){return false}}
function fallbackClose(el){if(!el)return false;if(reusable.has(el.id)){el.classList.remove('show','open','active','visible','expanded','chatOpen','localPanel','legalPanel','themePanel');el.removeAttribute('aria-hidden');el.hidden=false;el.innerHTML='';return true}try{el.querySelectorAll('video,audio').forEach(m=>{m.pause();m.muted=true})}catch(e){}try{el.remove();return true}catch(e){try{el.style.display='none';return true}catch(_){return false}}}
function closeOverlay(el){if(!el)return false;
 if(el.id==='previewModal'&&window.ITH&&typeof ITH.closePreview==='function'){ITH.closePreview();return true}
 if(el.id==='plusSheet'){if(window.ITH&&typeof ITH.closePlusMenuV249429==='function')ITH.closePlusMenuV249429('escape');else fallbackClose(el);return true}
 if(el.id==='memberMenu'){
   const b=nativeBack(el);if(b&&safeClick(b))return true;
   if(window.ITH&&typeof ITH.closeMember==='function'){ITH.closeMember();return true}
 }
 if(el.id==='ith477StoryViewer'){const b=el.querySelector('.ith477StoryClose');if(safeClick(b))return true}
 if(el.id==='creatorAnalyticsPanel410'&&window.ITH&&typeof ITH.closeCreatorAnalyticsV249410==='function'){ITH.closeCreatorAnalyticsV249410();return true}
 const b=nativeBack(el);if(b&&safeClick(b))return true;
 const c=nativeClose(el);if(c&&safeClick(c))return true;
 return fallbackClose(el)
}
function memberFeedActive(){return !!(document.body&&document.body.classList.contains('memberFeedV249485'))||window.__ITHAKI_MEMBER_FEED_MODE_V249483__===true||window.__ITHAKI_MEMBER_FEED_MODE_V249481__===true}
function backPage(){
 if(memberFeedActive()){const b=$('ithMemberFeedExitV249485');if(b)return safeClick(b);const f=window.ITH&&(ITH.closeMemberFeedV249494||ITH.closeMemberFeed);if(typeof f==='function'){f();return true}}
 const s=window.state||{};if(currentPage==='dm'&&s.activePeer&&window.ITH&&typeof ITH.showDMFriendListV249235==='function'){ITH.showDMFriendListV249235();s.activePeer='';s.activeChannel='';return true}
 if(currentPage!=='home'&&window.ITH&&typeof ITH.page==='function'){const dest=previousPage&&previousPage!==currentPage?previousPage:'home';previousPage='home';ITH.page(dest);return true}
 return false
}
function handleBack(){const o=topOverlay();if(o)return closeOverlay(o);return backPage()}
function ensureCss(){if($('ithNavigationCss502'))return;const st=document.createElement('style');st.id='ithNavigationCss502';st.textContent=`
.ithEscape392{display:none!important}.ithEscape502{position:fixed;top:max(10px,env(safe-area-inset-top));left:max(10px,env(safe-area-inset-left));z-index:2147483647;width:46px;height:46px;border-radius:50%;border:1px solid rgba(255,224,143,.62);background:rgba(3,15,25,.88);color:#ffe39a;box-shadow:0 12px 34px rgba(0,0,0,.48);display:grid;place-items:center;font:1000 27px/1 system-ui;padding:0;cursor:pointer;backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px)}.ithEscape502[hidden]{display:none!important}.ithEscape502:active{transform:scale(.94)}
.ithScroll501{max-height:calc(100dvh - 14px)!important;overflow-y:auto!important;overflow-x:hidden!important;overscroll-behavior:contain!important;-webkit-overflow-scrolling:touch!important}.ithFormScroll501{max-height:calc(100dvh - 100px)!important;overflow-y:auto!important;overflow-x:hidden!important;overscroll-behavior:contain!important;-webkit-overflow-scrolling:touch!important;padding-bottom:max(18px,env(safe-area-inset-bottom))!important}
#dmPage,#profilePage,#createPage,#spacesPage{overflow-y:auto!important;overscroll-behavior:contain!important;-webkit-overflow-scrolling:touch!important}@media(max-width:760px){.ithEscape502{width:44px;height:44px;font-size:25px}.ithScroll501{max-height:calc(100dvh - 8px)!important}.ithFormScroll501{max-height:calc(100dvh - 80px)!important}}
`;document.head.appendChild(st)}
function ensureMemberMenuBack(){const m=$('memberMenu');if(!m||!visible(m)||!m.classList.contains('show'))return false;const head=m.querySelector('.postHead,.memberHead,.modalHead')||m.firstElementChild;if(!head||nativeBack(m))return false;let b=m.querySelector('[data-v249502-member-back]');if(!b){b=document.createElement('button');b.type='button';b.className='icon ithMemberBack502';b.setAttribute('data-v249502-member-back','1');b.setAttribute('aria-label','Πίσω');b.textContent='‹';b.onclick=e=>{e.preventDefault();e.stopPropagation();if(window.ITH&&typeof ITH.closeMember==='function')ITH.closeMember();else fallbackClose(m)};head.insertBefore(b,head.firstChild)}return true}
function ensureDmBack(){const page=$('dmPage');if(!page||!visible(page))return false;const s=window.state||{},active=!!(s.activePeer||s.activeChannel||page.classList.contains('chatOpen')||page.querySelector('.dmConversation,.chatConversation,.messagesChat'));if(!active)return false;const head=page.querySelector('.chatHead,.dmChatHead,.messagesHeader,.chatHeader,.panelHead')||page.querySelector('.card,.panel');if(!head||nativeBack(head))return false;let b=head.querySelector('[data-v249502-dm-back]');if(!b){b=document.createElement('button');b.type='button';b.className='icon ithDmBack502';b.setAttribute('data-v249502-dm-back','1');b.setAttribute('aria-label','Πίσω στις επαφές');b.textContent='‹';b.onclick=e=>{e.preventDefault();e.stopPropagation();if(window.ITH&&typeof ITH.showDMFriendListV249235==='function')ITH.showDMFriendListV249235();else if(window.ITH&&typeof ITH.clearChat==='function')ITH.clearChat();try{s.activePeer='';s.activeChannel=''}catch(_){}};head.insertBefore(b,head.firstChild)}return true}
function ensureButton(){let b=$('ithGlobalEscapeV249502');if(!b){b=document.createElement('button');b.id='ithGlobalEscapeV249502';b.type='button';b.className='ithEscape502';b.textContent='‹';b.setAttribute('aria-label','Πίσω / κλείσιμο');b.title='Πίσω';b.onclick=e=>{e.preventDefault();e.stopPropagation();handleBack()};document.body.appendChild(b)}return b}
function activePage(){return document.querySelector('.page.active')||$(currentPage+'Page')||null}
function decorate(){ensureCss();ensureMemberMenuBack();ensureDmBack();const o=topOverlay();overlays().forEach(el=>{const box=scrollBoxes.map(s=>{try{return el.matches(s)?el:el.querySelector(s)}catch(e){return null}}).find(Boolean)||el.firstElementChild||el;box.classList.add('ithScroll501');box.querySelectorAll('form,.panelBody,.modalBody,.creatorPanelBody,.profilePanelBody').forEach(x=>x.classList.add('ithFormScroll501'))});const b=ensureButton();const native=o?nativeBack(o):nativeBack(activePage()||document.body);b.hidden=!!native||(!o&&currentPage==='home'&&!memberFeedActive());b.setAttribute('data-mode',o?'overlay':(memberFeedActive()?'member-feed':'page'))}
function updatePage(){const p=String(document.body&&document.body.getAttribute('data-page')||window.state&&state.page||'home');if(p&&p!==currentPage){previousPage=currentPage||'home';currentPage=p}decorate()}
function install(){ensureCss();currentPage=String(document.body&&document.body.getAttribute('data-page')||window.state&&state.page||'home');previousPage='home';ensureButton();
 const ob=new MutationObserver(()=>{if(updating)return;updating=true;requestAnimationFrame(()=>{updating=false;updatePage()})});ob.observe(document.body,{subtree:true,childList:true,attributes:true,attributeFilter:['class','hidden','style','aria-hidden','data-page']});
 document.addEventListener('keydown',e=>{if(e.key==='Escape'&&handleBack()){e.preventDefault();e.stopImmediatePropagation()}},true);
 window.ITH=window.ITH||{};Object.assign(ITH,{handleBackV249392:handleBack,handleBackV249501:handleBack,handleBackV249502:handleBack,closeTopMenuV249392:handleBack,closeTopMenuV249501:handleBack,closeTopMenuV249502:handleBack,refreshScrollableFormsV249392:decorate,refreshScrollableFormsV249501:decorate,refreshScrollableFormsV249502:decorate,navigationUiVersionV249392:VERSION,navigationUiVersionV249501:VERSION,navigationUiVersionV249502:VERSION});
 window.handleIthakiBackV249392=handleBack;window.handleIthakiBackV249501=handleBack;window.handleIthakiBackV249502=handleBack;
 document.documentElement.setAttribute('data-ithaki-navigation-ui','V249502');document.documentElement.setAttribute('data-ithaki-all-tabs-escape','YES');document.documentElement.setAttribute('data-ithaki-avatar-menu-back','YES');document.documentElement.setAttribute('data-ithaki-dm-back','YES');
 updatePage();setInterval(updatePage,1000)
}
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',install,{once:true});else install();
})();
