/* V249405-remove-feed-gate-preview-diagnostic */
(function(){'use strict';
const MARK='V249405-remove-feed-gate-preview-diagnostic';
const $=id=>document.getElementById(id), enc=encodeURIComponent;
const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const mb=n=>{n=Number(n||0);return n>=1048576?(n/1048576).toFixed(1)+' MB':Math.max(1,Math.round(n/1024))+' KB'};
function diag(action,extra){try{const row={t:new Date().toISOString(),action:String(action||''),page:(window.ITH&&ITH.state&&ITH.state.page)||document.body?.getAttribute('data-page')||'',extra:extra||null};const arr=JSON.parse(localStorage.getItem('ithaki_diag_v249405')||'[]')||[];arr.push(row);while(arr.length>120)arr.shift();localStorage.setItem('ithaki_diag_v249405',JSON.stringify(arr));console.warn('[ITHAKI V249405]',action,extra||'');}catch(e){}}
function S(){try{window.ITH=window.ITH||{};window.ITH.state=window.ITH.state||window.state||{};const s=window.ITH.state;s.room=s.room||localStorage.getItem('ith_room')||'ithaki-phone-test';s.device=s.device||localStorage.getItem('ith_device')||localStorage.getItem('device_id')||'';s.name=s.name||localStorage.getItem('ith_name')||localStorage.getItem('ith_nickname')||'Μέλος';s.api=s.api||location.origin;return s}catch(e){return {room:'ithaki-phone-test',device:'',name:'Μέλος',api:location.origin}}}
const base=()=>String((S()&&S().api)||location.origin).replace(/\/$/,''); const url=p=>base()+p;
function kindOf(file,kind){const t=String(file&&file.type||'').toLowerCase(),n=String(file&&file.name||'').toLowerCase(),k=String(kind||'').toLowerCase();if(k==='video'||t.startsWith('video/')||/\.(mp4|mov|m4v|webm|3gp|3gpp|avi|mkv)$/i.test(n))return 'video';if(k==='photo'||k==='image'||t.startsWith('image/'))return 'photo';if(k==='audio'||t.startsWith('audio/'))return 'audio';return 'file'}
function ensureCss(){if($('ithV249405Css'))return;const st=document.createElement('style');st.id='ithV249405Css';st.textContent=`#ithakiMemberGate382{display:none!important;visibility:hidden!important;pointer-events:none!important;opacity:0!important}html[data-ithaki-preview-v249405="1"] #previewModal.show{position:fixed!important;inset:0!important;z-index:2147483647!important;display:flex!important;align-items:flex-start!important;justify-content:center!important;overflow:auto!important;background:rgba(1,4,9,.78)!important;padding:18px!important;pointer-events:auto!important}#previewModal.show .previewSafeV249405{width:min(780px,96vw)!important;max-height:none!important;margin:auto!important;background:rgba(8,13,22,.97)!important;border:1px solid rgba(255,213,111,.34)!important;border-radius:24px!important;box-shadow:0 28px 90px rgba(0,0,0,.65)!important;padding:14px!important;overflow:visible!important}.v249405SafeStage{min-height:210px!important;display:flex!important;align-items:center!important;justify-content:center!important;border-radius:20px!important;background:linear-gradient(135deg,rgba(255,213,111,.14),rgba(255,255,255,.05))!important;border:1px solid rgba(255,213,111,.17)!important;text-align:center!important}.previewLiteV249405 .bigIcon{font-size:64px!important;margin-bottom:10px!important}.previewLiteV249405 b{display:block!important;color:#ffe49b!important;overflow-wrap:anywhere!important}.previewLiteV249405 small,.previewLiteV249405 .date{display:block!important;margin-top:8px!important;color:#d7dde8!important;opacity:.9!important}.homeStoriesV249405Fallback{border:1px solid rgba(255,255,255,.08)!important;background:rgba(255,255,255,.05)!important;border-radius:22px!important;margin:8px 0 12px!important;padding:8px!important;overflow:hidden!important}.homeStoriesV249405Fallback .storyScroll{display:flex!important;gap:10px!important;overflow-x:auto!important;padding:4px!important}.homeStoriesV249405Fallback .storyItem{min-width:72px!important;max-width:86px!important;background:transparent!important;border:0!important;color:#f5f7fa!important;text-align:center!important}.homeStoriesV249405Fallback .avatar{width:52px!important;height:52px!important;border-radius:50%!important;display:flex!important;align-items:center!important;justify-content:center!important;background:rgba(255,255,255,.1)!important;overflow:hidden!important;margin:auto!important}.homeStoriesV249405Fallback img{width:100%!important;height:100%!important;object-fit:cover!important}.homeStoriesV249405Fallback small{display:block!important;margin-top:5px!important;white-space:nowrap!important;overflow:hidden!important;text-overflow:ellipsis!important;font-size:11px!important}.homeMemberStatus405{font-size:12px!important;color:#ffe49b!important;padding:4px 8px!important}`;document.head.appendChild(st)}
function killMemberGate(){ensureCss();try{document.getElementById('ithakiMemberGate382')?.remove();document.documentElement.setAttribute('data-ithaki-feed-member-gate-removed','V249405');window.__ITHAKI_DISABLE_MEMBER_FEED_GATE_V249405=true;}catch(e){}}
function getOwnInput(){let inp=$('ithFileInputV249405');if(!inp){inp=document.createElement('input');inp.id='ithFileInputV249405';inp.type='file';inp.setAttribute('data-ithaki-owner','v249405');inp.style.cssText='position:fixed;left:-10000px;top:-10000px;width:1px;height:1px;opacity:0;pointer-events:none;';document.body.appendChild(inp)}return inp}
let previewUntil=0;
function protectPreview(){previewUntil=Date.now()+90000;try{document.documentElement.setAttribute('data-ithaki-preview-v249405','1')}catch(e){}}
function openPreview405(ctx,file,kind,target){ensureCss();killMemberGate();if(!file)return false;const s=S();kind=kindOf(file,kind);try{if(s.preview&&s.preview.url)URL.revokeObjectURL(s.preview.url)}catch(e){}s.preview={ctx:ctx||'feed',file,kind,target:target||'',originalFile:file,studio:null,url:'',desktopSafeV249405:true};try{s.sending=false}catch(e){}let m=$('previewModal');if(!m){m=document.createElement('div');m.id='previewModal';document.body.appendChild(m)}const icon=kind==='video'?'🎬':kind==='photo'?'🖼️':kind==='audio'?'🎙️':'📎';const dest=(ctx==='dm')?'στα Μηνύματα':(ctx==='space')?'στην Κοινότητα':(ctx==='comment'||ctx==='comment_frame')?'στα σχόλια':'στη Ροή';m.classList.remove('callCompactV249218','voiceCallV249218','videoCallV249218');m.innerHTML=`<div class="previewBox previewScrollable previewSafeV249405"><div class="row"><button class="icon" type="button" onclick="ITH.closePreview()">‹</button><b>Προεπισκόπηση ${esc(dest)}</b><button class="btn" type="button" onclick="ITH.closePreview()">Άκυρο</button></div><div id="previewStage" class="previewStage v249405SafeStage"><div class="previewLiteV249405"><div class="bigIcon">${icon}</div><b>${esc(file.name||'file')}</b><small>${esc(file.type||kind)} · ${mb(file.size)}</small><div class="date">V249405: χωρίς member-gate, χωρίς Studio/Canvas, χωρίς επιστροφή στην Αρχική.</div></div></div><div class="card previewFileCard"><b id="previewFileName">${esc(file.name||'file')}</b><div id="previewFileMeta" class="date">${esc(file.type||kind)} · ${mb(file.size)}</div></div><div id="previewStudioMount"></div><textarea id="previewCaption" rows="2" style="width:100%;min-height:72px;resize:vertical" placeholder="Λεζάντα..."></textarea><input id="previewKeywords" class="previewKeywordsV249287" placeholder="Λέξεις κλειδιά"><div class="previewHintV249287">Το αρχείο θα ανέβει μόνο όταν πατήσεις Αποστολή.</div>${ctx==='feed'?'<label class="card row anonymousRow"><input id="previewAnonymous" type="checkbox"><span class="anonBadge">🕶️ Ανώνυμη δημοσίευση</span></label>':''}<div class="progress"><span id="progressBar"></span></div><div id="progressText" class="date">Έτοιμο · ${mb(file.size)}</div><div class="row"><button id="previewSend" class="btn green" type="button" onclick="ITH.sendPreview()">Αποστολή / Δημοσίευση</button><button class="btn" type="button" onclick="ITH.closePreview()">Άκυρο</button></div></div>`;m.classList.add('show');document.body.classList.add('ithPreviewOpenV249405');protectPreview();diag('preview-open',{name:file.name,size:file.size,ctx,kind,target});return false}
function closePreview405(){try{const s=S();if(s.preview&&s.preview.url)URL.revokeObjectURL(s.preview.url);s.preview={}}catch(e){}const m=$('previewModal');if(m){m.classList.remove('show');m.innerHTML=''}document.body.classList.remove('ithPreviewOpenV249405');try{document.documentElement.removeAttribute('data-ithaki-preview-v249405')}catch(e){}previewUntil=0;diag('preview-close');return false}
function chooseFile405(ctx,kind,target){ensureCss();killMemberGate();const inp=getOwnInput();inp.value='';inp.removeAttribute('capture');inp.accept=kind==='video'?'video/*':kind==='photo'?'image/*':'*/*';inp.onchange=function(ev){try{ev&&ev.preventDefault&&ev.preventDefault();ev&&ev.stopPropagation&&ev.stopPropagation();ev&&ev.stopImmediatePropagation&&ev.stopImmediatePropagation()}catch(e){}const f=inp.files&&inp.files[0];diag('own-input-change',{hasFile:!!f,ctx,kind,target});if(!f)return false;return openPreview405(ctx||'feed',f,kind,target||'')};setTimeout(()=>{try{diag('own-input-click',{ctx,kind,target});inp.click()}catch(e){diag('own-input-click-error',String(e&&e.message||e))}},0);return false}
function captureMedia405(ctx,kind,target){ensureCss();killMemberGate();const inp=getOwnInput();inp.value='';inp.accept=kind==='video'?'video/*':'image/*';inp.setAttribute('capture','environment');inp.onchange=function(ev){try{ev&&ev.preventDefault&&ev.preventDefault();ev&&ev.stopPropagation&&ev.stopPropagation();ev&&ev.stopImmediatePropagation&&ev.stopImmediatePropagation()}catch(e){}inp.removeAttribute('capture');const f=inp.files&&inp.files[0];diag('capture-input-change',{hasFile:!!f,ctx,kind,target});if(!f)return false;return openPreview405(ctx||'feed',f,kind,target||'')};setTimeout(()=>inp.click(),0);return false}
function inferCtx(){try{const s=S();if(s.activePeer||String(s.page||'')==='dm')return 'dm'}catch(e){}return 'feed'}
function captureForeignFileInput(ev){try{const t=ev.target;if(!t||t.tagName!=='INPUT'||String(t.type||'').toLowerCase()!=='file')return;if(t.id==='ithFileInputV249405'||t.id==='profileAvatarFileV249512'||t.hasAttribute('data-profile-avatar-only-v249512'))return;const f=t.files&&t.files[0];if(!f)return;ev.preventDefault();ev.stopPropagation();ev.stopImmediatePropagation();diag('foreign-file-input-captured',{id:t.id||'',name:f.name});openPreview405(inferCtx(),f,kindOf(f,t.accept&&String(t.accept).includes('video')?'video':t.accept&&String(t.accept).includes('image')?'photo':'file'),'')}catch(e){diag('foreign-file-input-error',String(e&&e.message||e))}}
async function fetchJson405(path){const r=await fetch(url(path),{cache:'no-store',credentials:'same-origin'});if(!r.ok)throw new Error('HTTP '+r.status);return await r.json()}
function normalizePerson(p){const id=String(p&&(p.device_id||p.id||p.sender_id)||'').trim();if(!id||id===String(S().device||''))return null;return {id,device_id:id,nickname:String(p.nickname||p.name||'Μέλος'),avatar:String(p.avatar||p.photo||''),online:!!p.online,last_seen:Number(p.last_seen||p.created_at||0)}}
function storyAvatar(p){return p.avatar?`<span class="avatar"><img src="${esc(p.avatar)}" onerror="this.style.display='none'"></span>`:'<span class="avatar">👤</span>'}
function renderHomeMembers405(list,status){ensureCss();const home=$('homePage');if(!home)return;let box=$('homeStoriesV249405');if(!box){box=document.createElement('section');box.id='homeStoriesV249405';box.className='homeStoriesV249405Fallback';home.insertBefore(box,home.firstChild)}const people=(list||[]).filter(p=>p&&p.id&&p.id!==String(S().device||'')).slice(0,80);const ith='<button class="storyItem on" type="button" onclick="return ITH.page&&ITH.page(\'feed\')"><span class="avatar"><img src="ok_ithaki_ship_logo.png" onerror="this.style.display=\'none\'"></span><small>ΙΘΑΚΗ</small></button>';box.innerHTML=`<div class="homeMemberStatus405">Μέλη από server · ${esc(status||String(people.length)+' μέλη')}</div><div class="storyScroll">${ith}${people.map(p=>`<button class="storyItem ${p.online?'on':''}" type="button" onclick="return ITH.member&&ITH.member('${esc(p.id)}')">${storyAvatar(p)}<small>${esc(p.nickname||'Μέλος')}</small></button>`).join('')}</div>`}
async function loadHomeMembers405(){const s=S();let list=[];const errs=[];try{const k=await fetchJson405('/api/people/known?room_id='+enc(s.room||'ithaki-phone-test')+'&limit=800&_v='+Date.now());list=list.concat((k.people||[]).map(normalizePerson).filter(Boolean))}catch(e){errs.push('known:'+String(e.message||e))}try{const o=await fetchJson405('/api/people/online?room_id='+enc(s.room||'ithaki-phone-test')+'&_v='+Date.now());list=list.concat((o.people||[]).map(x=>normalizePerson(Object.assign({},x,{online:true}))).filter(Boolean))}catch(e){errs.push('online:'+String(e.message||e))}try{const f=await fetchJson405('/api/flow?room_id='+enc(s.room||'ithaki-phone-test')+'&visibility=public&limit=200&lite=1&viewer_id='+enc(s.device||'')+'&_v='+Date.now());list=list.concat((f.posts||[]).map(p=>normalizePerson({device_id:p.sender_id,nickname:p.nickname,avatar:p.avatar,last_seen:p.created_at})).filter(Boolean))}catch(e){errs.push('flow:'+String(e.message||e))}const map=new Map();list.forEach(p=>{if(!p||!p.id)return;const old=map.get(p.id)||{};map.set(p.id,Object.assign({},old,p,{avatar:p.avatar||old.avatar||'',online:p.online||old.online||false}))});list=[...map.values()].sort((a,b)=>(b.online-a.online)||String(a.nickname||'').localeCompare(String(b.nickname||''),'el'));try{const st=S();st.people=st.people||new Map();list.forEach(p=>st.people.set(p.id,Object.assign({},st.people.get(p.id)||{},p)))}catch(e){}renderHomeMembers405(list,errs.length?String(list.length)+' μέλη · fallback':String(list.length)+' μέλη');try{document.documentElement.setAttribute('data-ithaki-home-members-v249405',String(list.length))}catch(e){}diag('home-members-load',{count:list.length,errors:errs});return list}
async function syncFriends405(){const s=S();if(!s.device)return [];try{const r=await fetchJson405('/api/social/member_lists/v249405?room_id='+enc(s.room||'ithaki-phone-test')+'&device_id='+enc(s.device)+'&_v='+Date.now());const friends=Array.isArray(r.friends)?r.friends:[];try{s.socialFriendsV249225=friends;localStorage.setItem('ith_contacts_server_only_v249405','1');localStorage.removeItem('ith_contacts_local_merge_allowed');localStorage.setItem('ith_contacts',JSON.stringify([...new Set(friends.map(p=>String(p.device_id||p.id||'')).filter(Boolean))]))}catch(e){}diag('friends-sync',{count:friends.length});return friends}catch(e){try{s.socialFriendsV249225=[]}catch(_){}diag('friends-sync-error',String(e.message||e));return []}}
function safeStudio405(){const m=$('previewStudioMount');if(m)m.innerHTML='<div class="card"><b>Ασφαλής λειτουργία V249405</b><div class="date">Το βαρύ Studio/Canvas είναι κλειστό για να μη κολλάει ο υπολογιστής.</div></div>';return false}
function feedNoGate(){killMemberGate();diag('feed-open-no-gate');try{const I=window.ITH||{};if(typeof I.openRadicalFeedV249383==='function')return I.openRadicalFeedV249383();}catch(e){}try{if(typeof window.__ITHAKI_CANONICAL_FEED_V249357__==='function')return window.__ITHAKI_CANONICAL_FEED_V249357__()}catch(e){}try{if(window.state)window.state.page='feed';document.body&&document.body.setAttribute('data-page','feed');document.querySelectorAll('.page').forEach(p=>p.classList.remove('active'));const el=$('feedPage');if(el)el.classList.add('active')}catch(e){}return false}
function wrapPage(){try{const I=window.ITH||{};const old=I.page;if(old&&!old.__v249405){const fn=function(id){if(Date.now()<previewUntil&&String(id)==='home'){diag('blocked-home-redirect-during-preview');return false}if(String(id)==='feed')return feedNoGate();return old.apply(this,arguments)};fn.__v249405=1;I.page=fn;window.page=fn}}catch(e){diag('wrap-page-error',String(e.message||e))}}
function install(){ensureCss();killMemberGate();window.ITH=window.ITH||{};Object.assign(window.ITH,{openPreview:openPreview405,closePreview:closePreview405,chooseFile:chooseFile405,captureMedia:captureMedia405,openPreviewStudio:safeStudio405,loadHomeMembersV249405:loadHomeMembers405,refreshFriendsForMessagesV249246:syncFriends405,openFeedNoMemberGateV249405:feedNoGate});window.openPreview=openPreview405;window.chooseFile=chooseFile405;window.captureMedia=captureMedia405;window.__ITHAKI_ENTER_FEED_V249357__=feedNoGate;window.__ITHAKI_DISABLE_MEMBER_FEED_GATE_V249405=true;try{window.ITH.state=S()}catch(e){}wrapPage();try{document.documentElement.setAttribute('data-ithaki-v249405',MARK)}catch(e){}}
install();document.addEventListener('change',captureForeignFileInput,true);document.addEventListener('DOMContentLoaded',()=>{install();loadHomeMembers405();syncFriends405()},{once:true});let n=0;const timer=setInterval(()=>{install();killMemberGate();if(Date.now()<previewUntil){const m=$('previewModal');if(m&&!m.classList.contains('show'))m.classList.add('show')}if(++n>80)clearInterval(timer)},250);setTimeout(()=>{loadHomeMembers405();syncFriends405()},400);setTimeout(loadHomeMembers405,1600);setInterval(()=>{killMemberGate();loadHomeMembers405()},30000);window.__ITHAKI_V249405_DIAGNOSTIC__={install,diag,chooseFile405,openPreview405,loadHomeMembers405,syncFriends405,killMemberGate,feedNoGate,version:MARK};diag('installed');
})();
