/* OK ITHAKI V249519 - VISIBLE COMMUNITY TOOLBAR / MEDIA THUMBNAILS / HOME COMMUNITIES */
(function(){
'use strict';
if(window.__ITHAKI_V249519_VISIBLE_COMMUNITY_UI__)return;
window.__ITHAKI_V249519_VISIBLE_COMMUNITY_UI__={version:'V249519',visibleToolbar:true,homeCommunities:true,announcements:true,videoThumbnails:true,mediaGallery:true,at:Date.now()};
const I=()=>window.ITH||{},S=()=>window.state||I().state||{},$=id=>document.getElementById(id);
const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
function room(){return String(S().room||localStorage.getItem('ith_room')||'ithaki-phone-test')}
function sid(){return String(S().currentSpace||String(S().currentSpaceChannel||'').replace(/^space:/,''))}
function device(){return String(S().device||localStorage.getItem('ith_device')||'')}
function nickname(){return String(S().name||localStorage.getItem('ith_name')||localStorage.getItem('ith_nickname')||'Μέλος')}
function active(){return document.body?.getAttribute('data-page')==='spaces'&&!!sid()&&!!$('spaceMsgs')}
function base(){return location.origin.replace(/\/$/,'')}
function headers(json=false){const h={};if(json)h['Content-Type']='application/json';try{const t=localStorage.getItem('ith_public_token')||localStorage.getItem('ith_token')||'';if(t)h['X-ITHAKI-TOKEN']=t}catch(e){}return h}
async function api(path,opt={}){const r=await fetch(base()+path,Object.assign({cache:'no-store'},opt,{headers:Object.assign(headers(!!opt.body),opt.headers||{})}));const txt=await r.text();let d={};try{d=txt?JSON.parse(txt):{}}catch(e){d={detail:txt}}if(!r.ok)throw Error(typeof d.detail==='string'?d.detail:(d.message||('HTTP '+r.status)));return d}
function toast(m,ms=6500){try{if(I().toast)return I().toast(m,ms)}catch(e){}const t=$('toast');if(t){t.textContent=m;t.classList.add('show');setTimeout(()=>t.classList.remove('show'),ms)}else alert(m)}
function currentSpace(){return (S().spaces||[]).find(x=>String(x.subroom_id||'')===sid())||{subroom_id:sid(),role:'member',title:String($('spaceTitle')?.textContent||'Κοινότητα')}}
function role(){const x=currentSpace();return String(x.role||((x.is_owner||String(x.owner_id||'')===device())?'creator':'member'))}
function staffCode(){const r=role(),key=r==='moderator'?'ith_space_moderator_code_v249516_'+sid():'ith_space_creator_code_v249510_'+sid();let code='';try{code=localStorage.getItem(key)||''}catch(e){}if(!code&&['creator','moderator'].includes(r)){code=prompt(r==='moderator'?'Κωδικός συντονιστή:':'Κωδικός δημιουργού:')||'';if(code)try{localStorage.setItem(key,code)}catch(e){}}return code}
function addCss(){if($('ith519Css'))return;const st=document.createElement('style');st.id='ith519Css';st.textContent=`
#ith519CommunityCommandBar{flex:0 0 auto;display:flex;gap:7px;overflow-x:auto;overflow-y:hidden;padding:7px 8px;background:linear-gradient(90deg,rgba(4,17,29,.82),rgba(16,36,51,.70));border-bottom:1px solid rgba(255,217,110,.17);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);scrollbar-width:none;position:relative;z-index:8}#ith519CommunityCommandBar::-webkit-scrollbar{display:none}.ith519Cmd{flex:0 0 auto;min-width:78px;min-height:54px;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:3px;border-radius:16px;border:1px solid rgba(255,255,255,.12);background:rgba(255,255,255,.055);color:#fff;padding:6px 8px;touch-action:manipulation;box-shadow:0 7px 18px rgba(0,0,0,.16)}.ith519Cmd .ico{font-size:21px;line-height:1}.ith519Cmd .txt{font-size:10px;font-weight:900;white-space:nowrap}.ith519Cmd.gold{border-color:rgba(255,217,110,.48);background:rgba(255,217,110,.10)}.ith519Cmd.green{border-color:rgba(54,240,160,.43);background:rgba(54,240,160,.08)}.ith519Cmd.lockOn{border-color:#54f0a0;background:rgba(54,240,160,.15)}.ith519Cmd .badge{position:absolute;transform:translate(28px,-19px);min-width:18px;height:18px;padding:0 4px;border-radius:99px;background:#c62828;color:#fff;font-size:9px;display:grid;place-items:center;border:2px solid #07131f}.ith519Panel{position:fixed;inset:0;z-index:100100;background:rgba(3,9,16,.91);backdrop-filter:blur(12px);display:flex;flex-direction:column}.ith519PanelHead{display:flex;align-items:center;gap:8px;padding:9px;border-bottom:1px solid rgba(255,255,255,.12)}.ith519PanelHead b{flex:1;color:#ffe39b}.ith519PanelHead button{width:42px;height:42px;border-radius:50%;border:1px solid rgba(255,255,255,.14);background:rgba(255,255,255,.08);color:#fff;font-size:21px}.ith519PanelBody{flex:1;min-height:0;overflow:auto;padding:11px}.ith519Card{padding:12px;border-radius:17px;background:rgba(255,255,255,.055);border:1px solid rgba(255,255,255,.11);margin-bottom:9px;color:#fff}.ith519Card.announcement{border-color:rgba(255,217,110,.42);background:rgba(255,217,110,.08)}.ith519Primary{width:100%;min-height:54px;border-radius:17px;border:1px solid rgba(54,240,160,.48);background:rgba(54,240,160,.12);color:#fff;font-weight:950;margin-bottom:10px}.ith519VideoThumbStrip{display:flex;gap:6px;overflow-x:auto;padding:7px 5px 5px;background:rgba(0,0,0,.48);border-top:1px solid rgba(255,255,255,.10);scrollbar-width:none}.ith519VideoThumbStrip::-webkit-scrollbar{display:none}.ith519VideoThumb{flex:0 0 64px;width:64px;height:64px;padding:0;border-radius:12px;overflow:hidden;border:2px solid rgba(255,255,255,.16);background:#000;touch-action:manipulation}.ith519VideoThumb.current{border-color:#ffe39b}.ith519VideoThumb video,.ith519VideoThumb img{width:100%;height:100%;object-fit:cover;pointer-events:none;background:#000}.ith519MediaGrid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:7px}.ith519MediaTile{aspect-ratio:1/1;border:1px solid rgba(255,255,255,.13);border-radius:14px;overflow:hidden;background:#000;padding:0}.ith519MediaTile video,.ith519MediaTile img{width:100%;height:100%;object-fit:cover;pointer-events:none}.ith518MediaStage video{width:100%!important;height:min(62vh,640px)!important;min-height:220px!important;object-fit:contain!important;background:#000!important}.ith518MediaWrap{overflow:visible!important}.ith518MediaStage{overflow:hidden;border-radius:17px 17px 0 0}.ithHomeV249461 .ithActionV249461[data-v249461-route="spaces"] .ithActionIconV249461{background:linear-gradient(135deg,rgba(54,240,160,.30),rgba(255,217,110,.25))!important}
@media(max-width:680px){#ith519CommunityCommandBar{padding:6px}.ith519Cmd{min-width:70px;min-height:50px}.ith519MediaGrid{grid-template-columns:repeat(3,1fr)}.ith518MediaStage video{height:min(58vh,520px)!important;min-height:190px!important}}
`;document.head.appendChild(st)}
function panel(title,html){$('ith519Panel')?.remove();const d=document.createElement('div');d.id='ith519Panel';d.className='ith519Panel';d.innerHTML=`<div class="ith519PanelHead"><button data-ith519-close>‹</button><b>${esc(title)}</b><button data-ith519-close>×</button></div><div class="ith519PanelBody">${html}</div>`;document.body.appendChild(d);d.querySelectorAll('[data-ith519-close]').forEach(b=>b.onclick=()=>d.remove());return d}
function ensureHomeCard(){const home=$('homePage');if(!home)return;const buttons=[...home.querySelectorAll('.ithActionV249461')];let b=buttons.find(x=>/Κέντρο\s*Μηνυμάτων|Message\s*Center/i.test(x.textContent||''));if(!b)b=buttons.find(x=>x.getAttribute('data-v249461-action')==='external');if(!b)return;b.removeAttribute('data-v249461-action');b.setAttribute('data-v249461-route','spaces');b.setAttribute('data-ith-sun-color','blue');const ic=b.querySelector('.ithActionIconV249461');if(ic)ic.textContent='🏘️';const title=b.querySelector('b');if(title)title.textContent='Κοινότητες';const small=b.querySelector('small');if(small)small.textContent='Δωμάτια, μέλη, ψηφοφορίες και εκδηλώσεις';if(!b.__ith519){b.__ith519=true;b.addEventListener('click',e=>{e.preventDefault();e.stopImmediatePropagation();const f=I().activateSpacesPageV249516;if(typeof f==='function')return f();return I().page&&I().page('spaces')},true)}}
function lockOn(){try{return localStorage.getItem('ith_community_aes_enabled_v249518_'+room()+'_'+sid())==='1'&&!!localStorage.getItem('ith_community_aes_key_v249518_'+room()+'_'+sid())}catch(e){return false}}
function toolbarHtml(){const x=currentSpace(),r=role(),pins=Number(x.pinned_count||0),members=Number(x.member_count||0);return `<button class="ith519Cmd green" data-ith519-cmd="polls"><span class="ico">🗳️</span><span class="txt">Ψηφοφορία</span></button><button class="ith519Cmd gold" data-ith519-cmd="announcements"><span class="ico">📣</span><span class="txt">Ανακοινώσεις</span>${pins?`<i class="badge">${pins}</i>`:''}</button><button class="ith519Cmd ${lockOn()?'lockOn':''}" data-ith519-cmd="lock"><span class="ico">🔐</span><span class="txt">Κλειδαριά</span></button><button class="ith519Cmd" data-ith519-cmd="media"><span class="ico">🎞️</span><span class="txt">Πολυμέσα</span></button><button class="ith519Cmd" data-ith519-cmd="events"><span class="ico">📅</span><span class="txt">Εκδηλώσεις</span></button><button class="ith519Cmd" data-ith519-cmd="rules"><span class="ico">ℹ️</span><span class="txt">Κανόνες</span></button><button class="ith519Cmd" data-ith519-cmd="members"><span class="ico">👥</span><span class="txt">Μέλη${members?' '+members:''}</span></button>${['creator','moderator'].includes(r)?'<button class="ith519Cmd gold" data-ith519-cmd="manage"><span class="ico">🛡️</span><span class="txt">Διαχείριση</span></button>':''}`}
function ensureToolbar(){if(!active())return;const members=$('ith517MembersBar');if(!members)return;let bar=$('ith519CommunityCommandBar');if(!bar){bar=document.createElement('div');bar.id='ith519CommunityCommandBar';members.insertAdjacentElement('afterend',bar)}const next=toolbarHtml();if(bar.innerHTML!==next)bar.innerHTML=next;if(!bar.__bound){bar.__bound=true;bar.addEventListener('click',e=>{const b=e.target.closest('[data-ith519-cmd]');if(!b)return;e.preventDefault();e.stopPropagation();command(b.dataset.ith519Cmd)})}}
function parseBody(text){try{const o=JSON.parse(String(text||''));return String(o.body??o.text??text)}catch(e){return String(text||'')}}
async function openAnnouncements(){let d;try{d=await api('/api/rooms/pins?room_id='+encodeURIComponent(room())+'&subroom_id='+encodeURIComponent(sid()))}catch(e){return toast('Δεν φορτώθηκαν οι ανακοινώσεις: '+e.message)}const r=role(),can=['creator','moderator'].includes(r);let html=can?'<button class="ith519Primary" id="ith519NewAnnouncement">＋ ΝΕΑ ΑΝΑΚΟΙΝΩΣΗ</button>':'';html+=(d.pins||[]).map(p=>`<div class="ith519Card announcement"><b>📣 ${esc(p.note||'Ανακοίνωση')}</b><div style="white-space:pre-wrap;margin-top:7px">${esc(parseBody(p.text||''))}</div><small>${esc(p.nickname||'')} · ${new Date(Number(p.message_created_at||p.created_at||0)*1000).toLocaleString('el-GR')}</small></div>`).join('')||'<div class="ith519Card">Δεν υπάρχουν ακόμη ανακοινώσεις.</div>';const p=panel('📣 Ανακοινώσεις κοινότητας',html);p.querySelector('#ith519NewAnnouncement')?.addEventListener('click',createAnnouncement)}
async function createAnnouncement(){const r=role();if(!['creator','moderator'].includes(r))return toast('Μόνο δημιουργός ή συντονιστής μπορεί να δημοσιεύσει ανακοίνωση.');const title=prompt('Τίτλος ανακοίνωσης:')||'';if(!title)return;const body=prompt('Κείμενο ανακοίνωσης:')||'';if(!body)return;const code=staffCode();if(!code)return;try{await api('/api/rooms/announcements/create_v249519',{method:'POST',body:JSON.stringify({room_id:room(),subroom_id:sid(),device_id:device(),nickname:nickname(),staff_code:code,title,body})});toast('Η ανακοίνωση δημοσιεύτηκε και καρφιτσώθηκε.');$('ith519Panel')?.remove();const f=I().loadSpaceMessagesV249518||I().loadSpaceMessages;if(typeof f==='function')await f();openAnnouncements()}catch(e){toast('Δεν δημοσιεύτηκε: '+e.message,8000)}}
function mediaItems(){return [...document.querySelectorAll('#spaceMsgs .ith518Msg[data-mid]')].map(a=>{const v=a.querySelector('.ith518MediaStage video'),im=a.querySelector('.ith518MediaStage img');return v?{mid:a.dataset.mid,type:'video',src:v.currentSrc||v.src}:im?{mid:a.dataset.mid,type:'photo',src:im.currentSrc||im.src}:null}).filter(Boolean)}
function openMessageMedia(mid){$('ith519Panel')?.remove();const row=document.querySelector('#spaceMsgs .ith518Msg[data-mid="'+CSS.escape(String(mid))+'"]');if(!row)return;const full=row.querySelector('[data-ith518-action="full"]');if(full)full.click();else row.scrollIntoView({behavior:'smooth',block:'center'})}
function activateThumb(v){v.muted=true;v.playsInline=true;const seek=()=>{try{if(Number.isFinite(v.duration)&&v.duration>0)v.currentTime=Math.min(.15,v.duration/10)}catch(e){}};v.addEventListener('loadedmetadata',seek,{once:true});v.addEventListener('seeked',()=>v.pause(),{once:true})}
function openMediaGallery(){const items=mediaItems();let html='<div class="ith519MediaGrid">'+items.map(x=>`<button class="ith519MediaTile" data-ith519-media="${esc(x.mid)}">${x.type==='video'?`<video muted playsinline preload="metadata" src="${esc(x.src)}"></video>`:`<img loading="lazy" src="${esc(x.src)}" alt="">`}</button>`).join('')+'</div>';if(!items.length)html='<div class="ith519Card">Δεν υπάρχουν ακόμη φωτογραφίες ή βίντεο.</div>';const p=panel('🎞️ Πολυμέσα κοινότητας',html);p.querySelectorAll('[data-ith519-media]').forEach(b=>b.onclick=()=>openMessageMedia(b.dataset.ith519Media));p.querySelectorAll('video').forEach(activateThumb)}
function ensureVideoStrips(){if(!active())return;const items=mediaItems().filter(x=>x.type==='video').slice(-8);if(!items.length)return;document.querySelectorAll('#spaceMsgs .ith518Msg[data-mid]').forEach(row=>{const stage=row.querySelector('.ith518MediaStage'),v=stage?.querySelector('video');if(!v)return;const wrap=row.querySelector('.ith518MediaWrap');if(!wrap)return;let strip=wrap.querySelector('.ith519VideoThumbStrip');const signature=items.map(x=>x.mid).join('|');if(strip?.dataset.sig===signature)return;strip?.remove();strip=document.createElement('div');strip.className='ith519VideoThumbStrip';strip.dataset.sig=signature;strip.innerHTML=items.map(x=>`<button class="ith519VideoThumb ${x.mid===row.dataset.mid?'current':''}" data-ith519-thumb="${esc(x.mid)}" aria-label="Άνοιγμα βίντεο"><video muted playsinline preload="metadata" src="${esc(x.src)}"></video></button>`).join('');wrap.appendChild(strip);strip.querySelectorAll('[data-ith519-thumb]').forEach(b=>b.onclick=e=>{e.preventDefault();openMessageMedia(b.dataset.ith519Thumb)});strip.querySelectorAll('video').forEach(activateThumb)})}
function command(c){const o=I();if(c==='polls')return (o.openCommunityPollsV249518||o.openCommunityPollsV249516)?.();if(c==='announcements')return openAnnouncements();if(c==='lock')return o.openCommunitySharedLockV249518?.();if(c==='media')return openMediaGallery();if(c==='events')return o.openCommunityEventsV249516?.();if(c==='rules')return o.openCommunityInfoV249516?.();if(c==='members')return o.openCommunityMembersV249516?.();if(c==='manage')return o.openCommunityManagementV249516?.()}
function refresh(){addCss();ensureHomeCard();ensureToolbar();ensureVideoStrips()}
function wrapLoader(){const o=I();const old=o.loadSpaceMessagesV249518||o.loadSpaceMessages;if(typeof old!=='function'||old.__v249519)return;const w=async function(){const r=await old.apply(this,arguments);setTimeout(refresh,20);setTimeout(refresh,250);return r};w.__v249519=true;o.loadSpaceMessagesV249518=w;o.loadSpaceMessages=w;window.loadSpaceMessages=w}
function install(){addCss();try{const u=new URL(location.href);if(u.searchParams.get('v')!=='249524'){u.searchParams.set('v',(window.ITHAKI_ACTIVE_VERSION||'249526r10f37f1f2'));history.replaceState(null,'',u.pathname+'?'+u.searchParams.toString()+u.hash)}}catch(e){}wrapLoader();refresh();new MutationObserver(()=>{clearTimeout(install._m);install._m=setTimeout(refresh,60)}).observe(document.body,{subtree:true,childList:true});window.addEventListener('ithaki:page-changed',()=>setTimeout(refresh,80));window.addEventListener('pageshow',()=>setTimeout(refresh,50));setInterval(()=>{ensureHomeCard();if(active()){ensureToolbar();ensureVideoStrips()}},1500);Object.assign(I(),{openCommunityAnnouncementsV249519:openAnnouncements,openCommunityMediaGalleryV249519:openMediaGallery,refreshVisibleCommunityUiV249519:refresh});try{localStorage.setItem('ith_frontend_build','V249519-visible-community-toolbar-media-gallery-home-communities');document.documentElement.setAttribute('data-ithaki-v249519','visible-community-toolbar-media-gallery-home-communities')}catch(e){}}
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',install,{once:true});else install();
})();
