// ===== OK ITHAKI V249346 FINAL FIX: FEED + WALL + LEXICON =====
(function(){
  'use strict';
  if(window.__ITHAKI_V249346_FINAL__) return;
  window.__ITHAKI_V249346_FINAL__ = true;

  const BUILD='V249346';
  const TOKEN='OKITHAKI_PUBLIC_BETA_TOKEN_SERVER_ONLY_2026';
  const $=id=>document.getElementById(id);
  const q=(s,r=document)=>r.querySelector(s);
  const qa=(s,r=document)=>Array.from(r.querySelectorAll(s));
  const esc=s=>String(s??'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));
  const sleep=ms=>new Promise(r=>setTimeout(r,ms));

  function cleanBase(v){
    v=String(v||'').trim();
    return v.replace(/\/+$/,'');
  }
  function apiBase(){
    try{
      if(window.OKITHAKI_ANDROID&&typeof window.OKITHAKI_ANDROID.getServerBase==='function'){
        const v=cleanBase(window.OKITHAKI_ANDROID.getServerBase()); if(v) return v;
      }
    }catch(e){}
    try{
      if(window.AndroidBridge&&typeof window.AndroidBridge.getServerBase==='function'){
        const v=cleanBase(window.AndroidBridge.getServerBase()); if(v) return v;
      }
    }catch(e){}
    try{
      const keys=['ith_api_base','ith_lan_api_url','ith_last_detected_lan_url','ith_saved_local_base','ith_server_base'];
      for(const k of keys){ const v=cleanBase(localStorage.getItem(k)); if(/^https?:\/\//i.test(v)) return v; }
    }catch(e){}
    try{ if(/^https?:$/i.test(location.protocol)) return cleanBase(location.origin); }catch(e){}
    return 'https://ok-ithaki.gr';
  }
  function room(){ try{return localStorage.getItem('ith_room')||'ithaki-phone-test';}catch(e){return'ithaki-phone-test';} }
  function device(){ try{return localStorage.getItem('ith_device')||'dev_web';}catch(e){return'dev_web';} }
  async function request(path,opt={}){
    const headers=Object.assign({'X-ITHAKI-TOKEN':TOKEN},opt.headers||{});
    if(opt.body&&typeof opt.body==='string'&&!headers['Content-Type']) headers['Content-Type']='application/json';
    const res=await fetch(apiBase()+path,Object.assign({cache:'no-store'},opt,{headers}));
    let data={};
    try{data=await res.json();}catch(e){data={ok:false,message:'Invalid server response'};}
    if(!res.ok||data?.ok===false) throw new Error(data?.message||data?.detail||data?.note||('HTTP '+res.status));
    return data;
  }
  function notify(msg){
    try{
      const t=$('toast');
      if(t){t.textContent=msg;t.classList.add('show');clearTimeout(notify._t);notify._t=setTimeout(()=>t.classList.remove('show'),2800);return;}
    }catch(e){}
    console.log('[ITHAKI]',msg);
  }
  function viewportHeight(){
    const vv=window.visualViewport;
    return Math.max(420,Math.round((vv&&vv.height)||window.innerHeight||document.documentElement.clientHeight||720));
  }
  function setVh(){document.documentElement.style.setProperty('--ith-vh346',viewportHeight()+'px');}
  function pageIsFeed(){
    const f=$('feedPage');
    return document.body?.dataset?.page==='feed'||!!f?.classList.contains('active');
  }

  function injectCss(){
    if($('ithV249346Css')) return;
    const s=document.createElement('style');
    s.id='ithV249346Css';
    s.textContent=`
      :root{--ith-vh346:100dvh;--ith-gold346:#e1b857;--ith-gold2346:#ffe39a;--ith-ink346:#050a11}
      #ithBuild346{position:fixed;right:6px;bottom:calc(env(safe-area-inset-bottom,0px) + 5px);z-index:2147482000;padding:4px 7px;border-radius:999px;border:1px solid rgba(255,226,145,.28);background:rgba(0,0,0,.42);color:#ffe39a;font:900 9px/1 system-ui;pointer-events:none;opacity:.72}
      #ithGlobalTools346{position:fixed;right:10px;top:calc(env(safe-area-inset-top,0px) + 10px);z-index:2147482500;display:flex;gap:8px;pointer-events:auto}
      #ithGlobalTools346 button,#ithFeedToolbar346 button{touch-action:manipulation;-webkit-tap-highlight-color:transparent}
      #ithGlobalTools346 button{min-height:43px;border-radius:999px;border:1px solid rgba(255,226,145,.46);background:rgba(5,12,22,.88);color:#fff0bd;padding:0 13px;font:950 13px/1 system-ui;box-shadow:0 12px 32px rgba(0,0,0,.34);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px)}
      body[data-page="feed"] #ithGlobalTools346{display:none!important}

      #ithFeedToolbar346{position:fixed;left:50%;top:calc(env(safe-area-inset-top,0px) + 7px);transform:translateX(-50%);z-index:2147482600;width:min(980px,calc(100vw - 14px));display:none;grid-template-columns:auto minmax(120px,1fr) auto auto;gap:7px;align-items:center;padding:7px;border-radius:20px;border:1px solid rgba(255,255,255,.13);background:rgba(3,7,12,.76);box-shadow:0 14px 42px rgba(0,0,0,.42);backdrop-filter:blur(15px);-webkit-backdrop-filter:blur(15px)}
      body[data-page="feed"] #ithFeedToolbar346{display:grid}
      #ithFeedToolbar346 .ithBack346,#ithFeedToolbar346 .ithIcon346{height:42px;min-width:42px;border:0;border-radius:14px;background:rgba(255,255,255,.10);color:#fff;font:1000 20px/1 system-ui}
      #ithFeedToolbar346 .ithSearch346{height:42px;min-width:0;border-radius:14px;border:1px solid rgba(255,255,255,.13);background:rgba(0,0,0,.34);color:#fff;padding:0 13px;font:700 15px/1 system-ui;outline:none}
      #ithFeedToolbar346 .ithModes346{grid-column:1/-1;display:flex;gap:7px;overflow-x:auto;scrollbar-width:none;padding:1px}.ithModes346::-webkit-scrollbar{display:none}
      #ithFeedToolbar346 .ithModes346 button{flex:0 0 auto;min-height:36px;border-radius:999px;border:1px solid rgba(255,255,255,.12);background:rgba(255,255,255,.07);color:#dce3ee;padding:0 14px;font:900 13px/1 system-ui}
      #ithFeedToolbar346 .ithModes346 button.on{border-color:rgba(255,226,145,.65);background:linear-gradient(135deg,#b57a22,#e2b958);color:#171006}

      body[data-page="feed"]{overflow:hidden!important;background:#000!important;overscroll-behavior:none!important}
      body[data-page="feed"] #feedPage{position:fixed!important;inset:0!important;width:100vw!important;height:var(--ith-vh346)!important;min-height:var(--ith-vh346)!important;max-height:var(--ith-vh346)!important;margin:0!important;padding:0!important;border:0!important;border-radius:0!important;background:#000!important;overflow:hidden!important;z-index:1!important;transform:none!important}
      body[data-page="feed"] #feedPage>.feedBackOnly,body[data-page="feed"] #feedPage>.feedSearchGlassV249189,body[data-page="feed"] #feedPage>.feedToolbar332,body[data-page="feed"] #feedPage>[id^="feedTopBar"],body[data-page="feed"] #feedPage>[id^="feedSearchBar"],body[data-page="feed"] #feedPage .oldFeedBar{display:none!important;visibility:hidden!important;pointer-events:none!important}
      body[data-page="feed"] #feedPage .feedList{position:absolute!important;inset:0!important;width:100vw!important;height:var(--ith-vh346)!important;min-height:var(--ith-vh346)!important;max-height:var(--ith-vh346)!important;margin:0!important;padding:0!important;gap:0!important;background:#000!important;overflow-y:auto!important;overflow-x:hidden!important;scroll-snap-type:y mandatory!important;scroll-padding:0!important;overscroll-behavior-y:contain!important;-webkit-overflow-scrolling:touch!important;display:block!important;transform:none!important}
      body[data-page="feed"] #feedPage .ithFeedItem346{position:relative!important;width:100vw!important;max-width:none!important;height:var(--ith-vh346)!important;min-height:var(--ith-vh346)!important;max-height:var(--ith-vh346)!important;margin:0!important;padding:0!important;border:0!important;border-radius:0!important;background:#000!important;box-shadow:none!important;overflow:hidden!important;scroll-snap-align:start!important;scroll-snap-stop:always!important;box-sizing:border-box!important;transform:none!important}
      body[data-page="feed"] #feedPage .ithFeedItem346.ithHidden346{display:none!important}
      body[data-page="feed"] #feedPage .ithVideo346 .postMediaWrap,body[data-page="feed"] #feedPage .ithVideo346 .mediaInline,body[data-page="feed"] #feedPage .ithVideo346 [class*="mediaWrap" i]{position:absolute!important;inset:0!important;width:100%!important;height:100%!important;min-height:100%!important;max-height:100%!important;margin:0!important;padding:0!important;border:0!important;border-radius:0!important;background:#000!important;overflow:hidden!important;display:flex!important;align-items:center!important;justify-content:center!important}
      body[data-page="feed"] #feedPage .ithVideo346 video{display:block!important;width:100%!important;height:100%!important;min-height:100%!important;max-height:100%!important;object-fit:contain!important;object-position:center center!important;margin:0!important;padding:0!important;border:0!important;border-radius:0!important;background:#000!important;opacity:1!important;visibility:visible!important;transform:none!important}
      body[data-page="feed"] #feedPage .ithVideo346 .leftActions,body[data-page="feed"] #feedPage .ithVideo346 .feedAvatarOverlay,body[data-page="feed"] #feedPage .ithVideo346 .feedPreviewCommentOverlayV249296,body[data-page="feed"] #feedPage .ithVideo346 .postActions,body[data-page="feed"] #feedPage .ithVideo346 .textClamp,body[data-page="feed"] #feedPage .ithVideo346 .translateTools{position:relative!important;z-index:30!important}
      body[data-page="feed"] #feedPage .ithVideo346 .postHead{position:absolute!important;left:12px!important;right:12px!important;bottom:calc(env(safe-area-inset-bottom,0px) + 82px)!important;z-index:31!important;margin:0!important;padding:8px 10px!important;border-radius:16px!important;background:linear-gradient(90deg,rgba(0,0,0,.60),rgba(0,0,0,.08))!important;pointer-events:auto!important}
      body[data-page="feed"] #feedPage .ithVideo346>.textClamp,body[data-page="feed"] #feedPage .ithVideo346>.translateTools{position:absolute!important;left:14px!important;right:80px!important;bottom:calc(env(safe-area-inset-bottom,0px) + 30px)!important;color:#fff!important;text-shadow:0 2px 8px #000!important;z-index:31!important}
      body[data-page="feed"] #feedPage .ithVideo346 .mediaOpenBtn,body[data-page="feed"] #feedPage .ithVideo346 .fileTools,body[data-page="feed"] #feedPage .ithVideo346 [class*="fullscreen" i],body[data-page="feed"] #feedPage .ithVideo346 [id*="fullscreen" i],body[data-page="feed"] #feedPage .ithVideo346 [class*="zoom" i],body[data-page="feed"] #feedPage .ithVideo346 [id*="zoom" i]{display:none!important;visibility:hidden!important;pointer-events:none!important}
      body[data-page="feed"] #feedPage .ithWisdom346{display:grid!important;place-items:center!important;padding:92px 18px calc(env(safe-area-inset-bottom,0px) + 82px)!important;background:radial-gradient(circle at 50% 20%,rgba(255,214,105,.16),transparent 38%),linear-gradient(165deg,#07111c,#020407 72%)!important}
      body[data-page="feed"] #feedPage .ithWisdom346>*{max-width:min(620px,92vw)!important}
      body[data-page="feed"] #feedPage .ithWisdom346 .textClamp,body[data-page="feed"] #feedPage .ithWisdom346 .wisdomText,body[data-page="feed"] #feedPage .ithWisdom346 [class*="wisdom" i]{display:block!important;max-height:none!important;overflow:visible!important;text-align:center!important;color:#ffe29a!important;font:800 clamp(24px,6vw,39px)/1.35 Georgia,serif!important;text-shadow:0 3px 18px rgba(0,0,0,.72)!important;padding:34px 24px!important;border-radius:28px!important;border:1px solid rgba(255,223,139,.38)!important;background:linear-gradient(145deg,rgba(74,48,8,.78),rgba(12,17,23,.90))!important;box-shadow:0 24px 72px rgba(0,0,0,.52),inset 0 1px 0 rgba(255,255,255,.10)!important}
      body[data-page="feed"] #feedPage .ithWisdom346 .postHead{justify-content:center!important}
      body[data-page="feed"] #feedPage .ithWisdom346 .postActions,body[data-page="feed"] #feedPage .ithWisdom346 .leftActions{position:relative!important;z-index:3!important}
      body[data-page="feed"] #ithFeedBackplate345{display:none!important}
      body[data-page="feed"] #nav,body[data-page="feed"] nav.nav{opacity:.16!important;z-index:100!important}

      .ithModal346{position:fixed;inset:0;z-index:2147483500;background:rgba(1,4,8,.96);color:#fff;font-family:system-ui,-apple-system,Segoe UI,sans-serif;overflow:auto;-webkit-overflow-scrolling:touch;overscroll-behavior:contain}.ithModal346 *{box-sizing:border-box}.ithModal346 button,.ithModal346 input,.ithModal346 textarea,.ithModal346 select{font:inherit}.ithClose346{position:fixed;right:12px;top:calc(env(safe-area-inset-top,0px) + 10px);z-index:20;width:44px;height:44px;border-radius:50%;border:1px solid rgba(255,225,143,.45);background:rgba(0,0,0,.62);color:#fff;font-size:26px;font-weight:900}
      .lexShell346{min-height:var(--ith-vh346);padding:calc(env(safe-area-inset-top,0px) + 66px) 13px calc(env(safe-area-inset-bottom,0px) + 36px);background:radial-gradient(circle at 50% 0,rgba(222,180,81,.22),transparent 34%),linear-gradient(155deg,#081524,#03070d 70%,#010204)}
      .lexPanel346{width:min(900px,100%);margin:0 auto;display:grid;gap:12px;padding:16px;border-radius:26px;border:1px solid rgba(255,224,142,.28);background:rgba(5,13,23,.86);box-shadow:0 24px 76px rgba(0,0,0,.48)}
      .lexHead346{display:flex;align-items:center;gap:11px}.lexHead346 .book{font-size:38px}.lexHead346 h1{margin:0;color:#ffe094;font-size:clamp(24px,6vw,36px)}.lexHead346 p{margin:3px 0 0;color:#b9c3d0}
      .lexLang346{display:grid;grid-template-columns:1fr auto 1fr;gap:8px;align-items:center}.lexLang346 select{height:46px;border-radius:14px;border:1px solid rgba(255,255,255,.14);background:#0b1725;color:#fff;padding:0 12px;font-weight:850}.lexSwap346{height:46px;width:48px;border-radius:14px;border:1px solid rgba(255,224,142,.35);background:rgba(225,184,87,.14);color:#ffe19a;font-size:20px;font-weight:1000}
      .lexGrid346{display:grid;grid-template-columns:1fr 1fr;gap:10px}.lexBox346{display:grid;gap:7px}.lexBox346 label{font-weight:900;color:#d9e2ed}.lexBox346 textarea{width:100%;min-height:150px;resize:vertical;border-radius:18px;border:1px solid rgba(255,255,255,.14);background:rgba(0,0,0,.27);color:#fff;padding:13px;font-size:17px;outline:none}.lexBox346 textarea:focus{border-color:rgba(255,224,142,.60)}
      .lexButtons346{display:flex;gap:8px;flex-wrap:wrap}.lexButtons346 button{min-height:46px;border-radius:14px;border:1px solid rgba(255,255,255,.14);background:rgba(255,255,255,.08);color:#fff;padding:0 15px;font-weight:950}.lexButtons346 .gold{border:0;background:linear-gradient(135deg,#b87820,#e4bd62);color:#160f05}.lexStatus346{padding:10px 12px;border-radius:14px;background:rgba(0,0,0,.25);border:1px solid rgba(255,255,255,.09);color:#c5cfdb;min-height:42px}.lexSaved346{display:grid;gap:8px;max-height:310px;overflow:auto}.lexRow346{display:grid;grid-template-columns:minmax(0,1fr) auto minmax(0,1fr) auto;gap:8px;align-items:center;padding:10px;border-radius:16px;border:1px solid rgba(255,255,255,.09);background:rgba(255,255,255,.045)}.lexRow346 span{overflow-wrap:anywhere}.lexRow346 b{color:#ffe094}.lexRow346 button{width:38px;height:38px;border-radius:12px;border:0;background:rgba(255,80,80,.16);color:#ffd1d1}

      .wallShell346{min-height:var(--ith-vh346);padding:calc(env(safe-area-inset-top,0px) + 58px) 12px calc(env(safe-area-inset-bottom,0px) + 26px);background:radial-gradient(circle at 50% 0,rgba(50,112,165,.25),transparent 34%),radial-gradient(circle at 0 60%,rgba(225,184,87,.14),transparent 28%),linear-gradient(160deg,#071421,#03070d 68%,#010204)}
      .wallWrap346{width:min(850px,100%);margin:0 auto}.wallHead346{text-align:center;padding:4px 8px 16px}.wallBrand346{display:flex;align-items:center;justify-content:center;gap:9px}.wallBrand346 img{width:46px;height:46px;border-radius:15px;object-fit:cover}.wallBrand346 b{font-size:26px}.wallBrand346 span{color:#e1b857;font-weight:1000}.wallHead346 h1{font-size:clamp(29px,7vw,43px);margin:8px 0 4px}.wallHead346 p{margin:0;color:#c5cfdb}.wallPrivacy346{margin-top:8px;color:#ffe094;font-weight:900;font-size:13px}.wallLive346{display:flex;justify-content:space-between;gap:10px;align-items:center;padding:10px 12px;margin-bottom:10px;border-radius:15px;background:rgba(0,0,0,.23);border:1px solid rgba(255,255,255,.08);color:#cbd4df;font-size:13px}.wallLive346 b{color:#8ee095}.wallList346{display:grid;gap:11px}.wallEmpty346,.wallCard346{border:1px solid rgba(255,225,143,.18);background:linear-gradient(145deg,rgba(15,31,47,.84),rgba(5,10,17,.82));border-radius:22px;padding:14px;box-shadow:0 14px 42px rgba(0,0,0,.30)}.wallEmpty346{text-align:center;color:#cbd4df;padding:30px 16px}.wallMeta346{display:flex;align-items:center;gap:10px}.wallMask346{width:43px;height:43px;border-radius:50%;display:grid;place-items:center;border:1px solid rgba(255,225,143,.40);background:rgba(225,184,87,.12);font-size:22px}.wallMeta346 b{font-size:17px}.wallMeta346 small{display:block;color:#aeb8c5}.wallText346{font-size:17px;line-height:1.45;color:#fff;white-space:pre-wrap;overflow-wrap:anywhere}.wallActions346{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:7px}.wallActions346 button{min-height:43px;border-radius:13px;border:1px solid rgba(255,255,255,.13);background:rgba(0,0,0,.22);color:#f4f0e6;padding:6px;font-weight:900}.wallActions346 b{color:#ffe094;margin-left:4px}.wallReport346{display:block;margin:8px auto 0;border:0;background:none;color:#aeb8c5}.wallComposer346{position:sticky;bottom:calc(env(safe-area-inset-bottom,0px) + 5px);z-index:8;margin-top:13px;padding:12px;border-radius:23px;border:1px solid rgba(255,225,143,.27);background:rgba(7,17,29,.96);box-shadow:0 -14px 44px rgba(0,0,0,.44);backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px)}.wallComposer346 textarea{width:100%;min-height:88px;max-height:170px;resize:vertical;border-radius:16px;border:1px solid rgba(255,255,255,.14);background:rgba(0,0,0,.26);color:#fff;padding:12px;font-size:16px;outline:none}.wallCounter346{text-align:right;color:#aeb8c5;font-size:12px}.wallButtons346{display:grid;grid-template-columns:auto 1fr;gap:9px;margin-top:8px}.wallButtons346 button{height:49px;border-radius:15px;font-weight:1000}.wallReload346{border:1px solid rgba(255,225,143,.36);background:#0a1624;color:#ffe094}.wallSend346{border:0;background:linear-gradient(135deg,#b87820,#e4bd62);color:#160f05}

      @media(max-width:700px){#ithFeedToolbar346{grid-template-columns:auto minmax(0,1fr) auto auto}.lexGrid346{grid-template-columns:1fr}.lexRow346{grid-template-columns:1fr auto}.lexRow346 .arrow{display:none}.wallActions346{grid-template-columns:1fr}.wallActions346 button{min-height:40px}}
    `;
    document.head.appendChild(s);
  }

  function removeOldBrokenUi(){
    [
      'ithBuild339','ithBuild340','ithBuild341','ithBuild342','ithBuild343','ithBuild344','ithBuild345','ithDiag345',
      'ithBook339','ithBook343','ithBook344','ithBook345','ithFeature343','ithFeature344','ithFeature345',
      'ithFeedBackplate345','ithLex345','ithWall345','ithTrueFeed341','ithTrueFeedList341','ithRestoreNote342'
    ].forEach(id=>{try{$(id)?.remove();}catch(e){}});
    qa('.ithOrigVideo345').forEach(v=>{v.classList.remove('ithOrigVideo345');v.style.removeProperty('opacity');v.style.removeProperty('pointer-events');});
    try{document.body.classList.remove('ithTrueFeedOn341');}catch(e){}
  }

  let feedMode='all';
  let feedSearch='';
  let feedObserver=null;
  let observedVideos=new Set();
  function isWisdom(card){
    const cls=(card.className||'').toString().toLowerCase();
    if(/wisdom|σοφ|quote|ithaki.?gold/.test(cls)) return true;
    if(card.querySelector('[class*="wisdom" i],[data-kind="wisdom"],[data-type="wisdom"]')) return true;
    const text=(card.textContent||'').trim().toLowerCase();
    return text.startsWith('σοφό')||text.startsWith('σοφα')||text.includes('σοφά λόγια')||text.includes('wise words');
  }
  function isMine(card){
    const me=device();
    const id=card.dataset?.sender||card.dataset?.senderId||card.getAttribute('data-owner')||card.getAttribute('data-author-id')||'';
    if(id&&String(id)===String(me)) return true;
    const mine=card.querySelector(`[data-sender-id="${CSS.escape(me)}"],[data-owner-id="${CSS.escape(me)}"]`);
    return !!mine;
  }
  function visibleByFilter(card){
    const video=!!card.querySelector('video');
    const wisdom=card.classList.contains('ithWisdom346');
    const allowed=video||wisdom;
    if(!allowed) return false;
    if(feedMode==='video'&&!video) return false;
    if(feedMode==='wisdom'&&!wisdom) return false;
    if(feedMode==='mine'&&!isMine(card)) return false;
    if(feedSearch){
      const hay=(card.textContent||'').toLocaleLowerCase('el-GR');
      if(!hay.includes(feedSearch)) return false;
    }
    return true;
  }
  function pauseAllExcept(active){
    qa('#feedPage video').forEach(v=>{
      try{
        if(v===active){v.muted=true;v.playsInline=true;v.setAttribute('playsinline','');v.setAttribute('webkit-playsinline','');v.play().catch(()=>{});}
        else v.pause();
      }catch(e){}
    });
  }
  function bindVideoObserver(list){
    if(feedObserver){try{feedObserver.disconnect();}catch(e){}}
    observedVideos.clear();
    if(!('IntersectionObserver' in window)) return;
    feedObserver=new IntersectionObserver(entries=>{
      let best=null;
      for(const e of entries){
        const v=e.target;
        if(e.isIntersecting&&e.intersectionRatio>=(best?.ratio||0)){best={v,ratio:e.intersectionRatio};}
        else if(!e.isIntersecting){try{v.pause();}catch(_){}}
      }
      if(best?.v) pauseAllExcept(best.v);
    },{root:list,threshold:[0,.25,.5,.7,.85,1]});
    qa('video',list).forEach(v=>{
      if(v.closest('.ithHidden346')) return;
      v.muted=true;v.playsInline=true;v.setAttribute('playsinline','');v.setAttribute('webkit-playsinline','');v.setAttribute('controlsList','nodownload nofullscreen noremoteplayback');
      try{v.disablePictureInPicture=true;v.disableRemotePlayback=true;}catch(e){}
      feedObserver.observe(v);observedVideos.add(v);
    });
  }
  function applyFeedFilter(list){
    let first=null;
    qa(':scope > *',list).forEach(card=>{
      if(!card.classList.contains('ithFeedItem346')) return;
      const show=visibleByFilter(card);
      card.classList.toggle('ithHidden346',!show);
      card.setAttribute('aria-hidden',show?'false':'true');
      if(show&&!first) first=card;
    });
    bindVideoObserver(list);
    return first;
  }
  function classifyFeedCard(card){
    if(!(card instanceof HTMLElement)) return;
    if(card.id==='ithFeedToolbar346') return;
    card.classList.add('ithFeedItem346');
    card.classList.remove('ithVideo346','ithWisdom346');
    if(card.querySelector('video')) card.classList.add('ithVideo346');
    else if(isWisdom(card)) card.classList.add('ithWisdom346');
  }
  function ensureFeedToolbar(){
    let bar=$('ithFeedToolbar346');
    if(!bar){
      bar=document.createElement('div');bar.id='ithFeedToolbar346';
      bar.innerHTML=`<button class="ithBack346" type="button" aria-label="Πίσω">‹</button><input class="ithSearch346" id="ithFeedSearch346" placeholder="Αναζήτηση στη Ροή"><button class="ithIcon346" type="button" data-action="lex" title="Λεξικό">📖</button><button class="ithIcon346" type="button" data-action="wall" title="Τοίχος">🧱</button><div class="ithModes346"><button class="on" data-mode="all">Όλα</button><button data-mode="video">Βίντεο</button><button data-mode="wisdom">Σοφά</button><button data-mode="mine">Δικά μου</button></div>`;
      document.body.appendChild(bar);
      q('.ithBack346',bar).onclick=()=>{
        try{if(window.ITH&&typeof window.ITH.page==='function')window.ITH.page('home');else history.back();}catch(e){history.back();}
      };
      q('[data-action="lex"]',bar).onclick=openLexicon;
      q('[data-action="wall"]',bar).onclick=openWall;
      q('#ithFeedSearch346',bar).addEventListener('input',e=>{feedSearch=String(e.target.value||'').trim().toLocaleLowerCase('el-GR');applyFeed();});
      q('.ithModes346',bar).addEventListener('click',e=>{
        const b=e.target.closest('button[data-mode]');if(!b)return;
        feedMode=b.dataset.mode||'all';qa('button[data-mode]',bar).forEach(x=>x.classList.toggle('on',x===b));
        const first=applyFeed();try{first?.scrollIntoView({block:'start'});}catch(_){ }
      });
    }
    return bar;
  }
  function applyFeed(){
    setVh();ensureFeedToolbar();
    const feed=$('feedPage');
    if(!feed||!pageIsFeed()){
      try{pauseAllExcept(null);}catch(e){}
      return null;
    }
    const list=q('.feedList',feed);
    if(!list) return null;
    qa(':scope > *',list).forEach(classifyFeedCard);
    const first=applyFeedFilter(list);
    return first;
  }

  const LEX_KEY='ith_lexicon_v249346';
  function lexEntries(){try{const a=JSON.parse(localStorage.getItem(LEX_KEY)||'[]');return Array.isArray(a)?a:[];}catch(e){return[];}}
  function saveLexEntries(a){try{localStorage.setItem(LEX_KEY,JSON.stringify(a.slice(0,600)));}catch(e){}}
  function renderLexList(){
    const box=$('lexSaved346');if(!box)return;
    const rows=lexEntries();
    box.innerHTML=rows.length?rows.map((r,i)=>`<div class="lexRow346"><span><b>${esc(r.source)}</b><small style="display:block;color:#9eabba">${esc((r.src||'').toUpperCase())}</small></span><span class="arrow">→</span><span>${esc(r.target)}<small style="display:block;color:#9eabba">${esc((r.dst||'').toUpperCase())}</small></span><button type="button" data-del="${i}" title="Διαγραφή">×</button></div>`).join(''):'<div class="lexStatus346">Δεν έχεις αποθηκεύσει ακόμη δικές σου λέξεις.</div>';
    box.onclick=e=>{const b=e.target.closest('button[data-del]');if(!b)return;const a=lexEntries();a.splice(Number(b.dataset.del),1);saveLexEntries(a);renderLexList();};
  }
  function detectSource(text){return /[Α-Ωα-ωάέήίόύώϊΐϋΰ]/.test(text)?'el':'en';}
  function pickTranslation(d,original){
    const vals=[d?.translated,d?.translation,d?.result,d?.output,d?.text];
    for(const v of vals){if(typeof v==='string'&&v.trim())return v.trim();}
    return original;
  }
  async function translateLexicon(){
    const input=String($('lexInput346')?.value||'').trim();if(!input)return notify('Γράψε πρώτα λέξη ή φράση.');
    const srcSel=$('lexSrc346')?.value||'auto';
    const src=srcSel==='auto'?detectSource(input):srcSel;
    let dst=$('lexDst346')?.value||'en';if(dst===src)dst=src==='el'?'en':'el';
    const out=$('lexOutput346'),status=$('lexStatus346');
    out.value='';status.textContent='Μετάφραση από το τοπικό λεξικό…';
    try{
      const d=await request('/api/bridge/translate',{method:'POST',body:JSON.stringify({text:input,source_lang:src,target_lang:dst,allow_external:false,translation_mode:'offline',mode:'offline'})});
      out.value=pickTranslation(d,input);
      status.textContent='Έτοιμο · '+src.toUpperCase()+' → '+dst.toUpperCase()+' · '+String(d.provider||'τοπικό λεξικό');
    }catch(err){
      const local=lexEntries().find(r=>String(r.source||'').toLocaleLowerCase('el-GR')===input.toLocaleLowerCase('el-GR')&&r.src===src&&r.dst===dst);
      out.value=local?.target||input;
      status.textContent=local?'Βρέθηκε στο προσωπικό λεξικό.':'Χωρίς σύνδεση: η άγνωστη λέξη έμεινε όπως είναι.';
      try{await request('/api/bridge/dictionary/log_unknown',{method:'POST',body:JSON.stringify({text:input,src_lang:src,dst_lang:dst,context:'translation_book_v249346'})});}catch(e){}
    }
  }
  async function saveLexiconPair(){
    const source=String($('lexInput346')?.value||'').trim();const target=String($('lexOutput346')?.value||'').trim();
    if(!source||!target)return notify('Χρειάζονται και η λέξη και η μετάφραση.');
    const srcSel=$('lexSrc346')?.value||'auto';const src=srcSel==='auto'?detectSource(source):srcSel;let dst=$('lexDst346')?.value||'en';if(dst===src)dst=src==='el'?'en':'el';
    const rows=lexEntries().filter(r=>!(r.source.toLocaleLowerCase('el-GR')===source.toLocaleLowerCase('el-GR')&&r.src===src&&r.dst===dst));
    rows.unshift({source,target,src,dst,created_at:Date.now()});saveLexEntries(rows);renderLexList();
    let server='Τοπικά αποθηκευμένο.';
    try{await request('/api/bridge/dictionary/add',{method:'POST',body:JSON.stringify({source,target,src_lang:src,dst_lang:dst,kind:source.includes(' ')?'phrase':'word'})});server='Αποθηκεύτηκε και στο λεξικό του server.';}catch(e){server='Αποθηκεύτηκε στη συσκευή· ο server δεν ήταν διαθέσιμος.';}
    $('lexStatus346').textContent=server;notify('Η μετάφραση αποθηκεύτηκε.');
  }
  function exportLexicon(){
    const blob=new Blob([JSON.stringify({version:BUILD,exported_at:new Date().toISOString(),entries:lexEntries()},null,2)],{type:'application/json;charset=utf-8'});
    const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='ITHAKI_LEXICON_V249346.json';document.body.appendChild(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},200);
  }
  function openLexicon(){
    closeModal('ithWall346');
    let root=$('ithLex346');
    if(!root){
      root=document.createElement('div');root.id='ithLex346';root.className='ithModal346';
      root.innerHTML=`<button class="ithClose346" type="button" aria-label="Κλείσιμο">×</button><main class="lexShell346"><section class="lexPanel346"><header class="lexHead346"><span class="book">📖</span><div><h1>Λεξικό ΙΘΑΚΗΣ</h1><p>Ελληνικά ↔ Αγγλικά, αποθήκευση άγνωστων λέξεων και προσωπικό βιβλίο.</p></div></header><div class="lexLang346"><select id="lexSrc346"><option value="auto">Αυτόματη γλώσσα</option><option value="el">Ελληνικά</option><option value="en">English</option></select><button class="lexSwap346" id="lexSwap346" type="button">⇄</button><select id="lexDst346"><option value="en">English</option><option value="el">Ελληνικά</option></select></div><div class="lexGrid346"><div class="lexBox346"><label for="lexInput346">Λέξη ή φράση</label><textarea id="lexInput346" placeholder="Γράψε εδώ..."></textarea></div><div class="lexBox346"><label for="lexOutput346">Μετάφραση</label><textarea id="lexOutput346" placeholder="Η μετάφραση θα εμφανιστεί εδώ..."></textarea></div></div><div class="lexButtons346"><button class="gold" id="lexTranslate346" type="button">Μετάφραση</button><button id="lexSavePair346" type="button">Αποθήκευση λέξης</button><button id="lexCopy346" type="button">Αντιγραφή</button><button id="lexExport346" type="button">Εξαγωγή βιβλίου</button></div><div class="lexStatus346" id="lexStatus346">Το λεξικό είναι έτοιμο.</div><div><b style="color:#ffe094">Προσωπικές λέξεις</b><div class="lexSaved346" id="lexSaved346"></div></div></section></main>`;
      document.body.appendChild(root);
      q('.ithClose346',root).onclick=()=>root.remove();
      $('lexTranslate346').onclick=translateLexicon;
      $('lexSavePair346').onclick=saveLexiconPair;
      $('lexCopy346').onclick=async()=>{const t=$('lexOutput346').value||'';try{await navigator.clipboard.writeText(t);notify('Αντιγράφηκε.');}catch(e){$('lexOutput346').select();document.execCommand('copy');}};
      $('lexExport346').onclick=exportLexicon;
      $('lexSwap346').onclick=()=>{const a=$('lexSrc346'),b=$('lexDst346');const av=a.value==='auto'?detectSource($('lexInput346').value||''):a.value;const bv=b.value;a.value=bv;b.value=av;const x=$('lexInput346').value;$('lexInput346').value=$('lexOutput346').value;$('lexOutput346').value=x;};
      $('lexInput346').addEventListener('keydown',e=>{if((e.ctrlKey||e.metaKey)&&e.key==='Enter')translateLexicon();});
    }
    renderLexList();
    setTimeout(()=>$('lexInput346')?.focus(),60);
    return false;
  }

  let wallSocket=null;
  let wallReloadTimer=0;
  function closeModal(id){try{$(id)?.remove();}catch(e){}}
  function wallWhen(ts){try{return new Date((Number(ts)||0)*1000).toLocaleString('el-GR',{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'});}catch(e){return'';}}
  function renderWallPosts(posts){
    const box=$('wallList346');if(!box)return;
    if(!Array.isArray(posts)||!posts.length){box.innerHTML='<div class="wallEmpty346">Ο Τοίχος είναι άδειος. Γράψε την πρώτη ανώνυμη σκέψη.</div>';return;}
    box.innerHTML=posts.map(p=>`<article class="wallCard346" data-post-id="${esc(p.post_id)}"><div class="wallMeta346"><div class="wallMask346">🎭</div><div><b>Ανώνυμος</b><small>${esc(wallWhen(p.created_at))}</small></div></div><p class="wallText346">${esc(p.text)}</p><div class="wallActions346"><button type="button" data-kind="support">❤️ Στήριξη <b>${Number(p.support)||0}</b></button><button type="button" data-kind="reply">💬 Απάντηση <b>${Number(p.replies)||0}</b></button><button type="button" data-kind="understand">🕯️ Κατανόηση <b>${Number(p.understand)||0}</b></button></div><button class="wallReport346" type="button" data-report="1">⚐ Αναφορά</button></article>`).join('');
  }
  async function loadWall(){
    const box=$('wallList346');if(!box)return;
    try{
      const d=await request('/api/wall/list_v249345?room_id='+encodeURIComponent(room())+'&limit=120');
      $('wallLive346').textContent=String(Number(d.live_now)||0);renderWallPosts(d.posts||[]);
    }catch(e){box.innerHTML='<div class="wallEmpty346">Δεν φορτώθηκε ο Τοίχος.<br><small>'+esc(e.message)+'</small></div>';}
  }
  async function sendWallPost(){
    const ta=$('wallText346');const text=String(ta?.value||'').trim();if(!text)return notify('Γράψε πρώτα κάτι.');
    const btn=$('wallSend346');btn.disabled=true;btn.textContent='Αποστολή…';
    try{await request('/api/wall/post_v249345',{method:'POST',body:JSON.stringify({room_id:room(),owner_token:device(),text})});ta.value='';$('wallCount346').textContent='0';await loadWall();notify('Η ανώνυμη ανάρτηση δημοσιεύτηκε.');}
    catch(e){notify('Δεν στάλθηκε: '+e.message);}
    finally{btn.disabled=false;btn.textContent='Δημοσίευση ➤';}
  }
  async function wallAction(card,kind,button){
    const post_id=card?.dataset?.postId;if(!post_id)return;
    try{
      const d=await request('/api/wall/react_v249345',{method:'POST',body:JSON.stringify({room_id:room(),owner_token:device(),post_id,kind})});
      const count=kind==='support'?d.support:kind==='understand'?d.understand:d.replies;q('b',button).textContent=String(Number(count)||0);
    }catch(e){notify('Δεν καταγράφηκε: '+e.message);}
  }
  async function reportWall(card){
    const post_id=card?.dataset?.postId;if(!post_id)return;
    try{await request('/api/wall/report_v249345',{method:'POST',body:JSON.stringify({room_id:room(),owner_token:device(),post_id,reason:'user_report'})});notify('Η αναφορά καταγράφηκε.');}
    catch(e){notify('Δεν στάλθηκε η αναφορά.');}
  }
  function connectWallLive(){
    try{if(wallSocket&&wallSocket.readyState<=1)return;const base=apiBase().replace(/^http/i,'ws');wallSocket=new WebSocket(base+'/ws/live_v249345');wallSocket.onmessage=e=>{try{const m=JSON.parse(e.data);if(String(m.type||'').startsWith('wall_')){clearTimeout(wallReloadTimer);wallReloadTimer=setTimeout(loadWall,120);}}catch(_){}};wallSocket.onclose=()=>{wallSocket=null;};}catch(e){}
  }
  function openWall(){
    closeModal('ithLex346');
    let root=$('ithWall346');
    if(!root){
      root=document.createElement('div');root.id='ithWall346';root.className='ithModal346';
      root.innerHTML=`<button class="ithClose346" type="button" aria-label="Κλείσιμο">×</button><main class="wallShell346"><div class="wallWrap346"><header class="wallHead346"><div class="wallBrand346"><img src="/ok_ithaki_ship_logo.png" onerror="this.style.display='none'" alt=""><div><b>OK</b><span> ITHAKI</span></div></div><h1>Ανώνυμος Τοίχος 🛡️</h1><p>Μοιράσου σκέψεις χωρίς να εμφανίζεται το όνομά σου.</p><div class="wallPrivacy346">⚓ Ανώνυμο μήνυμα · σεβασμός · αναφορά κακοποίησης</div></header><div class="wallLive346"><span>🟢 Ζωντανά τώρα: <b id="wallLive346">0</b></span><span>Πραγματικές αναρτήσεις</span></div><div class="wallList346" id="wallList346"><div class="wallEmpty346">Φόρτωση…</div></div><section class="wallComposer346"><textarea id="wallText346" maxlength="500" placeholder="Γράψε ανώνυμα..."></textarea><div class="wallCounter346"><span id="wallCount346">0</span> / 500</div><div class="wallButtons346"><button class="wallReload346" id="wallReload346" type="button">↻ Ανανέωση</button><button class="wallSend346" id="wallSend346" type="button">Δημοσίευση ➤</button></div></section></div></main>`;
      document.body.appendChild(root);
      q('.ithClose346',root).onclick=()=>root.remove();
      $('wallText346').oninput=e=>$('wallCount346').textContent=String(e.target.value.length);
      $('wallReload346').onclick=loadWall;$('wallSend346').onclick=sendWallPost;
      $('wallList346').onclick=e=>{const card=e.target.closest('.wallCard346');if(!card)return;const b=e.target.closest('button[data-kind]');if(b)return wallAction(card,b.dataset.kind,b);if(e.target.closest('button[data-report]'))return reportWall(card);};
    }
    loadWall();connectWallLive();setTimeout(()=>$('wallText346')?.focus(),80);return false;
  }

  function ensureGlobalUi(){
    injectCss();setVh();removeOldBrokenUi();ensureFeedToolbar();
    if(!$('ithBuild346')){const b=document.createElement('div');b.id='ithBuild346';b.textContent=BUILD;document.body.appendChild(b);}
    if(!$('ithGlobalTools346')){
      const g=document.createElement('div');g.id='ithGlobalTools346';g.innerHTML='<button type="button" data-open="lex">📖 Λεξικό</button><button type="button" data-open="wall">🧱 Τοίχος</button>';document.body.appendChild(g);
      g.onclick=e=>{const b=e.target.closest('button[data-open]');if(!b)return;b.dataset.open==='lex'?openLexicon():openWall();};
    }
  }

  let applyTimer=0;
  function scheduleApply(delay=30){clearTimeout(applyTimer);applyTimer=setTimeout(()=>{ensureGlobalUi();applyFeed();},delay);}
  function install(){
    ensureGlobalUi();applyFeed();
    window.ITH=window.ITH||{};
    Object.assign(window.ITH,{
      openLexiconV249346:openLexicon,
      openTranslationBookV249346:openLexicon,
      openWallV249346:openWall,
      openAnonymousWallV249346:openWall,
      fixFeedV249346:applyFeed,
      setFeedModeV249346:m=>{feedMode=['all','video','wisdom','mine'].includes(m)?m:'all';scheduleApply(0);}
    });
    window.openTranslationBookV249346=openLexicon;
    window.openWallV249346=openWall;
  }

  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',install,{once:true});else install();
  [100,350,900,1800,3200].forEach(t=>setTimeout(()=>scheduleApply(0),t));
  try{new MutationObserver(()=>scheduleApply(45)).observe(document.documentElement,{childList:true,subtree:true});}catch(e){}
  addEventListener('resize',()=>scheduleApply(0),{passive:true});
  addEventListener('orientationchange',()=>setTimeout(()=>scheduleApply(0),100),{passive:true});
  if(window.visualViewport)visualViewport.addEventListener('resize',()=>scheduleApply(0),{passive:true});
})();
// ===== END OK ITHAKI V249346 FINAL FIX =====
