/* OK ITHAKI V249516 - FULL COMMUNITY SUITE / SINGLE OWNER / ALL FILES */
(function(){
'use strict';
if(window.__ITHAKI_R7_COMMUNITY_CANONICAL_PENDING__) return;
if(window.__ITHAKI_V249516_STABLE_COMMUNITY_OPEN_TOOLS__) return;
window.__ITHAKI_V249516_STABLE_COMMUNITY_OPEN_TOOLS__={version:'V249516',singleOwner:true,stableOpen:true,fullCommunitySuite:true,allFiles:true,at:Date.now()};
window.__ITHAKI_V249516_COMMUNITY_SINGLE_OWNER__=true;

const I=()=>window.ITH||{};
const S=()=>window.state||I().state||{};
const $=id=>document.getElementById(id);
const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const CATS=[
 ['all','🧭','Όλες'],['general','💬','Γενικά'],['holidays','🏖️','Διακοπές'],['fashion','👗','Μόδα'],['hobbies','🧩','Χόμπι'],['landscapes','🏞️','Τοπία'],['travel','✈️','Ταξίδια'],['photography','📷','Φωτογραφία'],['music','🎵','Μουσική'],['art','🎨','Τέχνη'],['technology','💻','Τεχνολογία'],['engineering','⚙️','Μηχανικοί και τεχνίτες'],['sports','🏃','Αθλητισμός'],['cooking','🍲','Μαγειρική'],['nature','🌿','Φύση και κήπος'],['family','👨‍👩‍👧','Οικογένεια'],['support','🤝','Υποστήριξη'],['philosophy','🧠','Φιλοσοφία'],['books','📚','Βιβλία'],['local','📍','Τοπικές κοινότητες'],['other','✨','Άλλο']
];
const GREEK_TITLE={
 'Better world':'🌍 Καλύτερος κόσμος','Work and dignity':'🛠️ Εργασία και αξιοπρέπεια','Life philosophy':'🧭 Φιλοσοφία ζωής','Environment':'🌱 Περιβάλλον','Justice':'⚖️ Δικαιοσύνη','Studies and learning':'🎓 Σπουδές και μάθηση','Technology for people':'🤖 Τεχνολογία για τον άνθρωπο','Health and balance':'🫶 Υγεία και ισορροπία','Holidays':'🏖️ Διακοπές','Fashion':'👗 Μόδα','Hobbies':'🧩 Χόμπι','Landscapes':'🏞️ Τοπία'
};
let kind='community',cat='all',spaces=[],busy=false,createCat='general',createKind='community';
let view='list',activeSpace=null,openingId='',rendering=false,restoreTimer=0,observer=null;let communityLoadGeneration=0,communityLastSignature='';
function newerCommunityOwner516(){return !!window.__ITHAKI_V249517_MESSAGES_EXACT_COMMUNITY__||!!window.__ITHAKI_V249526R4_COMMUNITY_OWNER__}

function room(){return String(S().room||localStorage.getItem('ith_room')||'ithaki-phone-test')}
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 apiBase(){return location.origin.replace(/\/$/,'')}
async function api(path,opt={}){
 const h=Object.assign({'Content-Type':'application/json'},opt.headers||{});
 try{const t=localStorage.getItem('ith_public_token')||localStorage.getItem('ith_token')||'';if(t)h['X-ITHAKI-TOKEN']=t}catch(e){}
 const r=await fetch(apiBase()+path,Object.assign({cache:'no-store'},opt,{headers:h}));
 let d={};try{d=await r.json()}catch(e){d={detail:await r.text()}}
 if(!r.ok)throw Error(d.detail||('HTTP '+r.status));return d;
}
function toast(m,ms=5500){try{if(I().toast)return I().toast(m,ms);const t=$('toast');if(t){t.textContent=m;t.classList.add('show');setTimeout(()=>t.classList.remove('show'),ms);return}}catch(e){}alert(m)}
function title(x){const raw=String(x?.title_el||x?.title||'Κοινότητα').trim();return GREEK_TITLE[raw]||raw}
function desc(x){return String(x?.description_el||x?.description||'').trim()}
function catName(k){const c=CATS.find(x=>x[0]===k)||CATS[CATS.length-1];return c[1]+' '+c[2]}
function accessName(v){return v==='invite'?'Με αίτημα και έγκριση':v==='private_code'?'Με κωδικό μέλους':'Ανοιχτή'}
function iconFor(x){const c=CATS.find(c=>c[0]===String(x?.topic_category||'general'));return c?c[1]:((x?.space_kind||x?.category)==='room'?'🏠':'🌐')}
function randomCode(){const a='ABCDEFGHJKLMNPQRSTUVWXYZ23456789';let s='';if(window.crypto&&crypto.getRandomValues){const b=new Uint8Array(10);crypto.getRandomValues(b);for(const n of b)s+=a[n%a.length]}else for(let i=0;i<10;i++)s+=a[Math.floor(Math.random()*a.length)];return s}
function saveCreatorCode(id,code){try{localStorage.setItem('ith_space_creator_code_v249510_'+id,code)}catch(e){}}
function followKey(){return 'ith_space_subscriptions_v249281'}
function followedIds(){try{return JSON.parse(localStorage.getItem(followKey())||'[]')}catch(e){return[]}}
function isFollowed(id){return followedIds().includes(String(id))}
function saveFollow(id,on){let a=followedIds().map(String);if(on&&!a.includes(String(id)))a.push(String(id));if(!on)a=a.filter(x=>x!==String(id));try{localStorage.setItem(followKey(),JSON.stringify(a))}catch(e){}}

function addCss(){if($('ith516Css'))return;const st=document.createElement('style');st.id='ith516Css';st.textContent=`
body[data-page="spaces"] #spacesPage{height:calc(100dvh - var(--top) - var(--bar));min-height:0;overflow:hidden!important;padding:0!important}.ith516Shell{height:100%;min-height:0;display:block;overflow:hidden;padding:8px;box-sizing:border-box}.ith516Shell.viewChat .ith516ListScreen,.ith516Shell.viewCreate .ith516ListScreen{display:none!important}.ith516Shell.viewChat .ith516ChatScreen{display:flex!important}.ith516Shell.viewCreate .ith516CreateScreen{display:flex!important}
.ith516ListScreen{height:100%;min-height:0;display:flex;flex-direction:column;gap:8px;overflow:hidden}.ith516Hero{display:flex;align-items:center;gap:10px;padding:10px 12px;border-radius:20px;background:linear-gradient(135deg,rgba(255,217,110,.13),rgba(54,240,160,.08));border:1px solid rgba(255,217,110,.22);box-shadow:0 12px 38px rgba(0,0,0,.22)}.ith516Hero .ship{width:42px;height:42px;border-radius:16px;display:grid;place-items:center;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.12);font-size:23px}.ith516Hero .text{min-width:0;flex:1}.ith516Hero b{display:block;color:#ffd96e;font-size:17px}.ith516Hero small{display:block;color:rgba(238,247,255,.76);line-height:1.32}
.ith516CreateCta{position:relative!important;z-index:90!important;pointer-events:auto!important;touch-action:manipulation!important;width:100%;min-height:68px;border:2px solid rgba(255,217,110,.78)!important;border-radius:20px!important;padding:10px 15px!important;display:flex!important;align-items:center!important;gap:13px!important;text-align:left!important;background:linear-gradient(135deg,rgba(255,211,92,.28),rgba(54,240,160,.18))!important;color:#fff!important;box-shadow:0 10px 34px rgba(0,0,0,.28),0 0 0 3px rgba(255,217,110,.06)!important}.ith516CreateCta .plus{font-size:34px;line-height:1;color:#ffe18a}.ith516CreateCta b{display:block;font-size:17px;color:#ffe49c}.ith516CreateCta small{display:block;margin-top:2px;color:rgba(255,255,255,.80)}
.ith516Kinds{display:grid;grid-template-columns:1fr 1fr auto;gap:7px;position:relative;z-index:70}.ith516Kinds button{min-height:42px;pointer-events:auto!important;touch-action:manipulation!important}.ith516Cats{position:relative!important;z-index:80!important;display:flex;gap:7px;overflow-x:auto;overflow-y:hidden;padding:4px 2px 7px;scrollbar-width:none;pointer-events:auto!important;touch-action:pan-x!important}.ith516Cats::-webkit-scrollbar{display:none}.ith516CatBtn{position:relative!important;z-index:81!important;flex:0 0 auto;white-space:nowrap;border-radius:999px;padding:10px 13px;border:1px solid rgba(255,255,255,.17);background:rgba(255,255,255,.08);color:#fff;font-weight:900;pointer-events:auto!important;touch-action:manipulation!important;cursor:pointer}.ith516CatBtn.on{background:linear-gradient(135deg,rgba(54,240,160,.28),rgba(255,217,110,.22));border-color:rgba(255,217,110,.68);color:#ffe39b;box-shadow:0 0 0 2px rgba(255,217,110,.07)}
.ith516Tools{display:flex;gap:8px}.ith516Tools .search{flex:1;min-height:42px;border-radius:999px;padding:8px 13px;background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.12);color:#fff}.ith516List{flex:1 1 auto;min-height:0;overflow-y:auto!important;overflow-x:hidden!important;-webkit-overflow-scrolling:touch;padding:2px 2px 14px;touch-action:pan-y;overscroll-behavior:contain}.ith516Row{cursor:pointer;pointer-events:auto!important;touch-action:manipulation!important}.ith516Row .avatar{display:grid!important;place-items:center!important;background:linear-gradient(135deg,rgba(54,240,160,.18),rgba(255,217,110,.18))!important;color:#fff;font-size:22px}.ith516Row .who small{white-space:normal!important;line-height:1.25}.ith516Pills{display:flex;gap:5px;flex-wrap:wrap;margin-top:5px}.ith516Pill{font-size:10px;border-radius:999px;padding:3px 6px;background:rgba(255,255,255,.08)}
.ith516CreateScreen{height:100%;min-height:0;display:none;flex-direction:column;overflow:hidden;background:rgba(5,18,31,.98);border-radius:20px;border:1px solid rgba(255,217,110,.18)}.ith516CreateHead{flex:0 0 auto;display:flex;align-items:center;gap:9px;padding:10px;border-bottom:1px solid rgba(255,255,255,.10)}.ith516CreateHead b{font-size:18px;color:#ffe39b}.ith516CreateBody{flex:1 1 auto;min-height:0;overflow-y:auto;padding:12px;-webkit-overflow-scrolling:touch}.ith516CreateCard{display:grid;gap:12px;padding:13px;border-radius:18px;background:rgba(255,255,255,.055);border:1px solid rgba(255,255,255,.11)}.ith516CreateCard label{font-weight:850}.ith516CreateCard input,.ith516CreateCard textarea,.ith516CreateCard select{width:100%;box-sizing:border-box;margin-top:5px;min-height:44px;border-radius:14px}.ith516CreateCatGrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin-top:7px;position:relative;z-index:100;pointer-events:auto!important}.ith516CreateCat{position:relative!important;z-index:101!important;min-height:54px;border-radius:16px;border:1px solid rgba(255,255,255,.14);background:rgba(255,255,255,.07);color:#fff;font-weight:900;text-align:left;padding:10px;pointer-events:auto!important;touch-action:manipulation!important;cursor:pointer}.ith516CreateCat.on{border-color:rgba(255,217,110,.78);background:linear-gradient(135deg,rgba(255,217,110,.24),rgba(54,240,160,.18));color:#ffe39b;box-shadow:0 0 0 2px rgba(255,217,110,.08)}.ith516Submit{min-height:54px!important;font-size:16px!important;font-weight:950!important;border-radius:17px!important}.ith516Notice{padding:10px;border-radius:15px;background:rgba(255,211,105,.1);border:1px solid rgba(255,211,105,.22)}
.ith516ChatScreen{height:100%;min-height:0;display:none;flex-direction:column;overflow:hidden;background:rgba(4,17,29,.98);border-radius:19px}.ith516ChatScreen .chatPane{height:100%!important;min-height:0!important;display:flex!important;flex-direction:column!important;overflow:hidden!important}.ith516ChatScreen .chatHead{flex:0 0 auto!important;min-height:48px!important}.ith516ChatScreen .messages{flex:1 1 0!important;min-height:0!important;max-height:none!important;overflow-y:auto!important;-webkit-overflow-scrolling:touch!important}.ith516ChatScreen .composer{flex:0 0 auto!important;position:sticky!important;bottom:0!important;z-index:3!important;background:rgba(6,20,35,.96)!important;border-top:1px solid rgba(255,255,255,.10)!important;padding-bottom:calc(6px + env(safe-area-inset-bottom,0px))!important}.ith516ChatAvatar{width:40px;height:40px;border-radius:50%;display:grid;place-items:center;background:linear-gradient(135deg,rgba(54,240,160,.20),rgba(255,217,110,.18));border:1px solid rgba(255,217,110,.26);font-size:20px}.ith516ChatTitle{min-width:0;flex:1}.ith516ChatTitle b{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.ith516ChatTitle small{display:block;color:rgba(238,247,255,.65);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.ith516CommunityTools{flex:0 0 auto;display:flex;gap:6px;overflow-x:auto;padding:6px 7px;border-bottom:1px solid rgba(255,255,255,.08);scrollbar-width:none}.ith516CommunityTools::-webkit-scrollbar{display:none}.ith516CommunityTools button{flex:0 0 auto;min-height:36px;border-radius:999px;padding:7px 10px;font-size:12px;white-space:nowrap}.ith516MessageSearch{display:none;flex:0 0 auto;padding:7px;background:rgba(255,255,255,.045);border-bottom:1px solid rgba(255,255,255,.08)}.ith516MessageSearch.show{display:flex}.ith516MessageSearch input{width:100%;min-height:40px;border-radius:999px;padding:8px 12px;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.14);color:#fff}.ith516PanelList{display:grid;gap:8px;max-height:64vh;overflow:auto}.ith516PanelRow{display:flex;gap:9px;align-items:center;padding:10px;border-radius:15px;background:rgba(255,255,255,.055);border:1px solid rgba(255,255,255,.09)}.ith516PanelRow span{flex:1}.ith516Rules{white-space:pre-wrap;line-height:1.5}.ith516FollowOn{background:linear-gradient(135deg,#54f0a0,#91ffd0)!important;color:#09251a!important}.ith516Role{font-size:10px;border-radius:999px;padding:3px 7px;background:rgba(255,217,110,.14);color:#ffe39b}.ith516Answer{padding:7px 9px;border-radius:12px;background:rgba(255,255,255,.05);margin-top:5px;white-space:pre-wrap}.ith516PollOption{width:100%;display:flex;justify-content:space-between;gap:8px;margin:6px 0;min-height:42px}.ith516EventActions{display:flex;gap:6px;flex-wrap:wrap;margin-top:8px}.ith516StaffActions{display:flex;gap:5px;flex-wrap:wrap}.ith516JoinRules{max-height:22vh;overflow:auto;white-space:pre-wrap;line-height:1.45;padding:10px;border-radius:14px;background:rgba(255,217,110,.08)}
@media(max-width:760px){.ith516Shell{padding:6px}.ith516Hero{border-radius:17px;padding:8px 9px}.ith516Hero .ship{width:36px;height:36px;font-size:20px;border-radius:14px}.ith516CreateCta{min-height:64px}.ith516Kinds{grid-template-columns:1fr 1fr auto}.ith516Kinds button{font-size:12px;padding:7px}.ith516CreateCatGrid{grid-template-columns:1fr 1fr}.ith516ChatScreen .chatHead{height:48px!important;min-height:48px!important}.ith516ChatScreen .chatHead .optionalHeadAction{display:none!important}}
`;document.head.appendChild(st)}

function shellHtml(){return `<div id="ith516Shell" class="ith516Shell dmContactFirstShellV249235">
<section id="ith516ListScreen" class="ith516ListScreen dmFriendScreenV249235">
 <div class="ith516Hero dmFriendHeroV249235"><button type="button" class="icon" data-ith516-action="home">‹</button><div class="ship">🏘️</div><div class="text"><b>Χώροι και Κοινότητες</b><small>Διάλεξε κατηγορία και άνοιξε τη συζήτηση όπως ακριβώς στα Μηνύματα.</small></div></div>
 <button type="button" id="ith516CreateCta" class="ith516CreateCta" data-ith516-action="create"><span class="plus">＋</span><span><b>ΔΗΜΙΟΥΡΓΙΑ ΝΕΑΣ ΚΟΙΝΟΤΗΤΑΣ</b><small>Όνομα, κατηγορία, πρόσβαση και δικαιώματα δημιουργού</small></span></button>
 <div class="ith516Kinds"><button type="button" id="ith516RoomsBtn" class="btn" data-ith516-action="kind" data-kind="room">🏠 Δωμάτια</button><button type="button" id="ith516CommunitiesBtn" class="btn green" data-ith516-action="kind" data-kind="community">🌐 Όλες οι κοινότητες</button><button type="button" class="btn" data-ith516-action="reload">🔄</button></div>
 <div id="ith516Cats" class="ith516Cats"></div>
 <div class="ith516Tools dmFriendToolsV249235"><input id="ith516Search" class="search" placeholder="Αναζήτηση κοινότητας..."><button type="button" class="icon" data-ith516-action="reload">🔄</button></div>
 <div id="ith516List" class="ith516List dmFriendListV249235"></div>
</section>
<section id="ith516CreateScreen" class="ith516CreateScreen">
 <div class="ith516CreateHead"><button type="button" class="icon" data-ith516-action="close-create">‹</button><b id="ith516CreateTitle">Νέα κοινότητα</b><span class="spacer"></span><button type="button" class="icon" data-ith516-action="close-create">×</button></div>
 <div class="ith516CreateBody"><div class="ith516CreateCard">
  <label>Τίτλος<input id="ith516Title" maxlength="100" placeholder="Όνομα κοινότητας"></label>
  <label>Σύντομη περιγραφή<textarea id="ith516Desc" rows="3" placeholder="Τι συζητάμε σε αυτή την κοινότητα"></textarea></label>
  <label>Κανόνες κοινότητας<textarea id="ith516Rules" rows="4" placeholder="Σεβασμός, ασφάλεια, τι επιτρέπεται και τι όχι"></textarea></label>
  <label>Μήνυμα καλωσορίσματος<textarea id="ith516Welcome" rows="2" placeholder="Μήνυμα που θα βλέπει το νέο μέλος"></textarea></label>
  <div><b>Ερωτήσεις συμμετοχής — προαιρετικά, έως 3</b><input id="ith516Question1" maxlength="180" placeholder="1η ερώτηση"><input id="ith516Question2" maxlength="180" placeholder="2η ερώτηση"><input id="ith516Question3" maxlength="180" placeholder="3η ερώτηση"></div>
  <div><b>Κατηγορία</b><div id="ith516CreateCats" class="ith516CreateCatGrid"></div></div>
  <label>Πρόσβαση<select id="ith516Access"><option value="public">Ανοιχτή — μπαίνουν άμεσα</option><option value="invite">Με αίτημα και έγκριση δημιουργού</option><option value="private_code">Με κωδικό μέλους</option></select></label>
  <label>Κωδικός μέλους — μόνο για κλειστή κοινότητα<input id="ith516JoinCode" maxlength="40"></label>
  <label>Κωδικός δημιουργού<input id="ith516CreatorCode" maxlength="80"></label>
  <div class="ith516Notice">Ο κωδικός δημιουργού αποθηκεύεται στον server μόνο ως ασφαλές hash. Κράτησέ τον για αποδοχή, απόρριψη και μπλοκάρισμα μελών.</div>
  <button type="button" class="btn green ith516Submit" data-ith516-action="submit-create">✓ ΔΗΜΙΟΥΡΓΙΑ ΚΟΙΝΟΤΗΤΑΣ</button>
 </div></div>
</section>
<section id="ith516ChatScreen" class="ith516ChatScreen dmChatScreenV249235">
 <div class="chatPane">
  <div class="chatHead"><button type="button" class="icon" data-ith516-action="close-chat">‹</button><span id="ith516ChatAvatar" class="ith516ChatAvatar">🌐</span><div class="ith516ChatTitle"><b id="spaceTitle">Κοινότητα</b><small id="ith516ChatMeta">Ανοιχτή συζήτηση</small></div><button class="icon chatActionBtn optionalHeadAction" title="Φωτογραφία" onclick="ITH.openSpaceMedia('photo',true)">📷</button><button class="icon chatActionBtn optionalHeadAction" title="Βίντεο" onclick="ITH.openSpaceMedia('video',true)">🎥</button><button class="icon optionalHeadAction" title="Αρχείο" onclick="ITH.openSpaceMedia('file',false)">📎</button><button class="icon" title="Διαχείριση" data-ith516-action="manage">⚙️</button></div>
  <div class="ith516CommunityTools"><button class="btn" data-ith516-action="info">ℹ️ Κανόνες</button><button class="btn" data-ith516-action="members">👥 Μέλη</button><button class="btn" data-ith516-action="pins">📌 Καρφιτσωμένα</button><button class="btn" data-ith516-action="search-messages">🔎 Αναζήτηση</button><button id="ith516FollowBtn" class="btn" data-ith516-action="follow">🔔 Ειδοποιήσεις</button><button class="btn" data-ith516-action="invite">＋ Πρόσκληση</button><button class="btn" data-ith516-action="polls">🗳️ Ψηφοφορίες</button><button class="btn" data-ith516-action="events">📅 Εκδηλώσεις</button><button class="btn" data-ith516-action="manage">🛡️ Συντονισμός</button></div>
  <div id="ith516MessageSearch" class="ith516MessageSearch"><input id="ith516MessageSearchInput" placeholder="Αναζήτηση μέσα στη συζήτηση..."></div>
  <div id="spacePinnedBoxV249281"></div>
  <div id="spaceMsgs" class="messages"><div class="card">Διάλεξε κοινότητα ή δωμάτιο.</div></div>
  <div class="composer"><button class="icon" onclick="ITH.openSpaceMedia('file',false)">📎</button><textarea id="spaceInput" placeholder="Γράψε μήνυμα στην κοινότητα..."></textarea><button class="icon" onclick="ITH.sendSpaceText()">➤</button></div>
 </div>
</section>
</div>`}

function renderCats(){const h=$('ith516Cats');if(!h)return;h.style.display=kind==='community'?'flex':'none';h.innerHTML=CATS.map(c=>`<button type="button" class="ith516CatBtn ${cat===c[0]?'on':''}" data-ith516-action="category" data-category="${c[0]}">${c[1]} ${c[2]}</button>`).join('')}
function renderCreateCats(){const h=$('ith516CreateCats');if(!h)return;h.innerHTML=CATS.filter(c=>c[0]!=='all').map(c=>`<button type="button" class="ith516CreateCat ${createCat===c[0]?'on':''}" data-ith516-action="create-category" data-category="${c[0]}">${c[1]} ${c[2]}</button>`).join('')}
function applyView(){const sh=$('ith516Shell');if(!sh)return;sh.classList.toggle('viewChat',view==='chat');sh.classList.toggle('viewCreate',view==='create');if(view==='chat'&&activeSpace){const t=$('spaceTitle');if(t)t.textContent=title(activeSpace);const av=$('ith516ChatAvatar');if(av)av.textContent=iconFor(activeSpace);const m=$('ith516ChatMeta');if(m)m.textContent=catName(activeSpace.topic_category||'general')+' · '+accessName(activeSpace.access_type)+' · '+({creator:'Δημιουργός',moderator:'Συντονιστής',member:'Μέλος'}[activeSpace.role]||'Μέλος');updateFollowButton()}}
function bindActions(){const root=$('ith516Shell');if(!root||root.__ith516Bound)return;root.__ith516Bound=true;root.addEventListener('click',async e=>{const b=e.target.closest('[data-ith516-action]');if(!b||!root.contains(b))return;e.preventDefault();e.stopPropagation();e.stopImmediatePropagation();const a=b.dataset.ith516Action;
 if(a==='home')return I().page&&I().page('home');if(a==='kind')return setKind(b.dataset.kind);if(a==='category')return setCat(b.dataset.category);if(a==='create')return showCreate(kind);if(a==='create-category'){createCat=CATS.some(c=>c[0]===b.dataset.category)?b.dataset.category:'general';renderCreateCats();return false}if(a==='reload')return loadSpaces();if(a==='close-create')return closeCreate();if(a==='submit-create')return submitCreate();if(a==='open-space')return openSpace(b.dataset.spaceId);if(a==='close-chat')return closeChat();if(a==='info')return openInfo();if(a==='members')return openMembers();if(a==='pins')return openPins();if(a==='search-messages')return toggleMessageSearch();if(a==='follow')return toggleFollow();if(a==='invite')return inviteMembers();if(a==='polls')return openPolls();if(a==='events')return openEvents();if(a==='manage')return openManage();
 },true);const q=$('ith516Search');if(q)q.addEventListener('input',renderList,{passive:true});const mq=$('ith516MessageSearchInput');if(mq)mq.addEventListener('input',filterMessages,{passive:true})}
function renderPage(){addCss();const page=$('spacesPage');if(!page)return false;rendering=true;document.body&&document.body.setAttribute('data-page','spaces');page.classList.add('active');page.innerHTML=shellHtml();bindActions();renderCats();renderCreateCats();updateKindButtons();applyView();if(!spaces.length)loadSpaces();else renderList();setTimeout(()=>{rendering=false},0);try{document.documentElement.setAttribute('data-ithaki-v249516-active','stable-community-open-tools')}catch(e){}return false}
function activateSpacesPage(){try{const s=S();s.page='spaces';window.state=s;window.ITH=window.ITH||{};window.ITH.state=s;view='list';activeSpace=null;document.body&&document.body.setAttribute('data-page','spaces');document.querySelectorAll('.page').forEach(p=>p.classList.remove('active'));const page=$('spacesPage');if(page)page.classList.add('active');document.querySelectorAll('.nav button').forEach(b=>b.classList.toggle('active',String(b.dataset.page||'')==='spaces'));$('plusSheet')?.classList.remove('show');renderPage();try{window.dispatchEvent(new CustomEvent('ithaki:page-changed',{detail:{page:'spaces',version:'V249516',owner:'v249516'}}))}catch(e){}return false}catch(e){toast('Δεν άνοιξαν οι κοινότητες: '+(e.message||e));return false}}
function updateKindButtons(){const rb=$('ith516RoomsBtn'),cb=$('ith516CommunitiesBtn'),cta=$('ith516CreateCta');if(rb)rb.classList.toggle('green',kind==='room');if(cb)cb.classList.toggle('green',kind==='community');if(cta){cta.querySelector('b').textContent=kind==='room'?'ΔΗΜΙΟΥΡΓΙΑ ΝΕΟΥ ΔΩΜΑΤΙΟΥ':'ΔΗΜΙΟΥΡΓΙΑ ΝΕΑΣ ΚΟΙΝΟΤΗΤΑΣ';cta.querySelector('small').textContent=kind==='room'?'Όνομα, κατηγορία και πρόσβαση δωματίου':'Όνομα, κατηγορία, πρόσβαση και δικαιώματα δημιουργού'}}
function communityCanonicalKey516(x){const titleKey=String(title(x)||'').normalize('NFD').replace(/[\u0300-\u036f]/g,'').replace(/\s+/g,' ').trim().toLocaleLowerCase('el');const kindKey=String(x?.space_kind||x?.category||'community');const id=String(x?.subroom_id||x?.space_id||x?.id||'').trim();return titleKey?kindKey+':'+titleKey:(id?'id:'+id:'')}
function dedupeCommunityRows516(list){const m=new Map();for(const raw of Array.isArray(list)?list:[]){const x=Object.assign({},raw),k=communityCanonicalKey516(x);if(!k)continue;if(!m.has(k)){m.set(k,x);continue}const p=m.get(k);m.set(k,Object.assign({},p,x,{member_count:Math.max(Number(p.member_count||0),Number(x.member_count||0)),message_count:Math.max(Number(p.message_count||0),Number(x.message_count||0)),is_member:!!(p.is_member||x.is_member),is_owner:!!(p.is_owner||x.is_owner),blocked:!!(p.blocked&&x.blocked)}))}return Array.from(m.values())}
function communitySignature516(list){return dedupeCommunityRows516(list).map(x=>communityCanonicalKey516(x)).sort().join('|')}
async function loadSpaces(force=false){if(busy&&!force)return false;const seq=++communityLoadGeneration;busy=true;try{const d=await api('/api/rooms/overview_v249510?room_id='+encodeURIComponent(room())+'&device_id='+encodeURIComponent(device()));if(seq!==communityLoadGeneration)return false;const next=dedupeCommunityRows516(d.rooms||[]),sig=communitySignature516(next);spaces=next;const s=S();s.spaces=spaces;if(sig!==communityLastSignature||force){communityLastSignature=sig;renderList()}document.documentElement.setAttribute('data-ithaki-community-response-count',String((d.rooms||[]).length));document.documentElement.setAttribute('data-ithaki-community-dedup-count',String(spaces.length));return true}catch(e){if(seq===communityLoadGeneration){const l=$('ith516List');if(l)l.innerHTML='<div class="card">Δεν φορτώθηκαν οι κοινότητες: '+esc(e.message)+'</div>'}return false}finally{if(seq===communityLoadGeneration)busy=false}}
function filtered(){const q=String($('ith516Search')?.value||'').trim().toLocaleLowerCase('el');return dedupeCommunityRows516(spaces.filter(x=>{const k=String(x.space_kind||x.category||'community');if(k!==kind)return false;if(kind==='community'&&cat!=='all'&&String(x.topic_category||'general')!==cat)return false;if(q&&!String(title(x)+' '+desc(x)+' '+catName(x.topic_category||'general')).toLocaleLowerCase('el').includes(q))return false;return true}))}
function renderList(){const l=$('ith516List');if(!l)return;const arr=filtered();l.innerHTML=arr.map(x=>{const id=String(x.subroom_id||'');const status=x.blocked?'Μπλοκαρισμένη':(x.is_member?'Είσαι μέλος':accessName(x.access_type));return `<div role="button" tabindex="0" class="dmFriendRowV249235 ith516Row" data-ith516-action="open-space" data-space-id="${esc(id)}"><span class="avatar">${iconFor(x)}</span><span class="who"><b>${esc(title(x))}</b><small>${esc(desc(x)||catName(x.topic_category||'general'))}</small><span class="ith516Pills"><span class="ith516Pill">${esc(catName(x.topic_category||'general'))}</span><span class="ith516Pill">👥 ${Number(x.member_count||0)}</span><span class="ith516Pill">💬 ${Number(x.message_count||0)}</span><span class="ith516Pill">${esc(status)}</span></span></span><span class="go"><span class="msgGo">💬 Άνοιγμα</span></span></div>`}).join('')||'<div class="card dmEmptyV249235">Δεν βρέθηκαν κοινότητες σε αυτή την κατηγορία.</div>'}
function setKind(v){kind=v==='room'?'room':'community';cat='all';view='list';updateKindButtons();renderCats();const s=$('ith516Search');if(s)s.placeholder=kind==='room'?'Αναζήτηση δωματίου...':'Αναζήτηση κοινότητας...';renderList();return false}
function setCat(v){cat=CATS.some(c=>c[0]===v)?v:'all';renderCats();renderList();return false}
function showCreate(v){createKind=v==='room'?'room':'community';createCat='general';view='create';applyView();const t=$('ith516CreateTitle');if(t)t.textContent=createKind==='room'?'Νέο δωμάτιο':'Νέα κοινότητα';const code=$('ith516CreatorCode');if(code)code.value=randomCode();const titleInput=$('ith516Title');if(titleInput)titleInput.value='';const descInput=$('ith516Desc');if(descInput)descInput.value='';['ith516Rules','ith516Welcome','ith516Question1','ith516Question2','ith516Question3'].forEach(id=>{const e=$(id);if(e)e.value='' });const join=$('ith516JoinCode');if(join)join.value='';const access=$('ith516Access');if(access)access.value='public';renderCreateCats();setTimeout(()=>titleInput?.focus(),60);return false}
function closeCreate(){view='list';applyView();return false}
async function submitCreate(){const titleValue=String($('ith516Title')?.value||'').trim(),creator=String($('ith516CreatorCode')?.value||'').trim();if(!titleValue)return toast('Βάλε τίτλο στην κοινότητα.');if(creator.length<6)return toast('Ο κωδικός δημιουργού θέλει τουλάχιστον 6 χαρακτήρες.');const questions=['ith516Question1','ith516Question2','ith516Question3'].map(id=>String($(id)?.value||'').trim()).filter(Boolean);const btn=document.querySelector('[data-ith516-action="submit-create"]');if(btn){btn.disabled=true;btn.textContent='Δημιουργία...'}try{const d=await api('/api/rooms/create_v249516',{method:'POST',body:JSON.stringify({room_id:room(),owner_id:device(),owner_name:nickname(),title:titleValue,description:String($('ith516Desc')?.value||''),rules_text:String($('ith516Rules')?.value||''),welcome_text:String($('ith516Welcome')?.value||''),membership_questions:questions,space_kind:createKind,topic_category:createCat,access_type:$('ith516Access')?.value||'public',join_code:String($('ith516JoinCode')?.value||''),creator_code:creator})});saveCreatorCode(d.subroom_id,creator);toast('Η κοινότητα δημιουργήθηκε πλήρως. Κράτησε τον κωδικό δημιουργού: '+creator,9000);kind=createKind;cat=createCat;await loadSpaces();view='list';applyView();renderCats();updateKindButtons();renderList();return false}catch(e){toast('Δεν δημιουργήθηκε: '+e.message,7000);return false}finally{if(btn){btn.disabled=false;btn.textContent=createKind==='room'?'✓ ΔΗΜΙΟΥΡΓΙΑ ΔΩΜΑΤΙΟΥ':'✓ ΔΗΜΙΟΥΡΓΙΑ ΚΟΙΝΟΤΗΤΑΣ'}}}
function ensureChatVisible(){if(view!=='chat'||!activeSpace)return;if(!$('ith516Shell'))renderPage();view='chat';applyView()}
async function loadMessagesStable(){ensureChatVisible();const box=$('spaceMsgs');if(box)box.innerHTML='<div class="card">Φόρτωση μηνυμάτων…</div>';try{const f=I().loadSpaceMessages||window.loadSpaceMessages;if(typeof f==='function')await Promise.resolve(f.call(I(),true));else throw Error('load unavailable')}catch(e){try{const r=await api('/api/messages?room_id='+encodeURIComponent(room())+'&channel='+encodeURIComponent('space:'+activeSpace.subroom_id)+'&since=0&limit=300');const b=$('spaceMsgs');if(b){b.innerHTML=(r.messages||[]).map(m=>`<div class="bubble ${String(m.sender_id||'')===device()?'mine':''}"><b>${esc(m.nickname||'Μέλος')}</b><div class="msgBody">${esc(m.text||'')}</div><div class="meta">${esc(m.created_at||'')}</div></div>`).join('')||'<div class="card">Ξεκίνα τη συνομιλία του χώρου.</div>';b.scrollTop=b.scrollHeight}}catch(_e){const b=$('spaceMsgs');if(b)b.innerHTML='<div class="card">Δεν φορτώθηκαν τα μηνύματα.</div>'}}finally{ensureChatVisible();setTimeout(ensureChatVisible,80)}}
function staffCodeKey(id,role){return role==='moderator'?'ith_space_moderator_code_v249516_'+id:'ith_space_creator_code_v249510_'+id}
function getStaffCode(id,role){try{return localStorage.getItem(staffCodeKey(id,role))||''}catch(e){return''}}
function setStaffCode(id,role,code){try{localStorage.setItem(staffCodeKey(id,role),code)}catch(e){}}
async function enterSpaceChat(x,detail){const s=S();s.spaces=spaces;s.currentSpace=String(x.subroom_id);s.currentSpaceChannel='space:'+x.subroom_id;activeSpace=Object.assign({},x,detail?.room||{});view='chat';applyView();try{I().wsSubscribe&&I().wsSubscribe(s.currentSpaceChannel)}catch(e){}await loadMessagesStable();if(activeSpace.welcome_text)toast(activeSpace.welcome_text,6500);setTimeout(()=>$('spaceInput')?.focus(),80);return false}
function openJoinPanel(x,detail){const r=detail.room||{};const qs=Array.isArray(r.membership_questions)?r.membership_questions:[];const inputs=qs.map((q,i)=>`<label><b>${esc(q)}</b><textarea id="ith516JoinAnswer${i}" rows="2"></textarea></label>`).join('');const code=r.access_type==='private_code'?'<label><b>Κωδικός μέλους</b><input id="ith516JoinCodePrompt"></label>':'';panel('Συμμετοχή · '+title(x),`<div class="card"><b>Κανόνες</b><div class="ith516JoinRules">${esc(r.rules_text||desc(x)||'Σεβασμός και ασφάλεια για όλα τα μέλη.')}</div></div>${inputs}${code}<label class="ith516PanelRow"><input id="ith516AcceptRules" type="checkbox"><span>Διάβασα και αποδέχομαι τους κανόνες.</span></label><button id="ith516JoinSubmit" class="btn green">✓ ΣΥΜΜΕΤΟΧΗ</button>`);setTimeout(()=>{const b=$('ith516JoinSubmit');if(b)b.addEventListener('click',async()=>{b.disabled=true;try{const answers=qs.map((_,i)=>String($('ith516JoinAnswer'+i)?.value||'').trim());const d=await api('/api/rooms/join_v249516',{method:'POST',body:JSON.stringify({room_id:room(),subroom_id:x.subroom_id,device_id:device(),nickname:nickname(),join_code:String($('ith516JoinCodePrompt')?.value||''),answers,rules_accepted:Boolean($('ith516AcceptRules')?.checked)})});if(d.pending){$('memberMenu')?.classList.remove('show','fullAvatarMenuV249231');toast('Το αίτημα και οι απαντήσεις στάλθηκαν στον δημιουργό.');return} $('memberMenu')?.classList.remove('show','fullAvatarMenuV249231');x.is_member=true;await enterSpaceChat(x,{room:Object.assign({},r,{role:'member',is_member:true})})}catch(e){toast('Δεν ολοκληρώθηκε η συμμετοχή: '+e.message,7000)}finally{b.disabled=false}}, {once:false})},30);return false}
async function openSpace(id){id=String(id||'');if(!id||openingId===id)return false;const x=spaces.find(s=>String(s.subroom_id)===id);if(!x)return toast('Δεν βρέθηκε η κοινότητα.');if(x.blocked)return toast('Δεν έχεις πρόσβαση σε αυτή την κοινότητα.');openingId=id;try{const detail=await api('/api/rooms/detail_v249516?room_id='+encodeURIComponent(room())+'&subroom_id='+encodeURIComponent(id)+'&device_id='+encodeURIComponent(device()));const r=detail.room||{};if(r.is_member||r.is_owner)return enterSpaceChat(x,detail);const needsPanel=(Array.isArray(r.membership_questions)&&r.membership_questions.length>0)||r.access_type!=='public'||String(r.rules_text||'').trim();if(needsPanel)return openJoinPanel(x,detail);const d=await api('/api/rooms/join_v249516',{method:'POST',body:JSON.stringify({room_id:room(),subroom_id:id,device_id:device(),nickname:nickname(),answers:[],rules_accepted:true})});if(d.pending){toast('Το αίτημα συμμετοχής στάλθηκε.');return false}x.is_member=true;return enterSpaceChat(x,{room:Object.assign({},r,{role:'member',is_member:true})})}catch(e){toast('Δεν άνοιξε η κοινότητα: '+e.message,7000);return false}finally{openingId=''}}
function closeChat(){view='list';activeSpace=null;const s=S();s.currentSpace='';s.currentSpaceChannel='';applyView();return false}
function panel(titleText,body){const m=$('memberMenu');if(!m)return false;m.innerHTML=`<div class="row"><button class="icon" data-ith516-panel-close>‹</button><b>${esc(titleText)}</b><button class="icon" style="margin-left:auto" data-ith516-panel-close>×</button></div><div class="ith516PanelList">${body}</div>`;m.classList.add('show','fullAvatarMenuV249231');m.querySelectorAll('[data-ith516-panel-close]').forEach(b=>b.addEventListener('click',()=>m.classList.remove('show','fullAvatarMenuV249231')));return false}
function openInfo(){if(!activeSpace)return false;return panel('ℹ️ Πληροφορίες και κανόνες',`<div class="card"><h3>${esc(title(activeSpace))}</h3><div class="ith516Pills"><span class="ith516Pill">${esc(catName(activeSpace.topic_category||'general'))}</span><span class="ith516Pill">${esc(accessName(activeSpace.access_type))}</span><span class="ith516Pill">👥 ${Number(activeSpace.member_count||0)}</span></div></div><div class="card"><b>Κανόνες / περιγραφή</b><div class="ith516Rules">${esc(activeSpace.rules_text||desc(activeSpace)||'Ο δημιουργός δεν έχει γράψει ακόμη κανόνες. Ισχύουν οι βασικοί κανόνες σεβασμού και ασφάλειας της ΙΘΑΚΗΣ.')}</div></div>`)}
async function openMembers(){if(!activeSpace)return false;panel('👥 Μέλη','<div class="card">Φόρτωση μελών…</div>');try{const d=await api('/api/rooms/members?room_id='+encodeURIComponent(room())+'&subroom_id='+encodeURIComponent(activeSpace.subroom_id));const html=(d.members||[]).map(m=>`<div class="ith516PanelRow"><span><b>${esc(m.nickname||'Μέλος')}</b><small>${esc(m.device_id||'')}</small></span></div>`).join('')||'<div class="card">Δεν εμφανίζονται μέλη ακόμη.</div>';panel('👥 Μέλη',html)}catch(e){panel('👥 Μέλη','<div class="card">Δεν φορτώθηκαν τα μέλη.</div>')}return false}
async function openPins(){if(!activeSpace)return false;panel('📌 Καρφιτσωμένα','<div class="card">Φόρτωση…</div>');try{const d=await api('/api/rooms/pins?room_id='+encodeURIComponent(room())+'&subroom_id='+encodeURIComponent(activeSpace.subroom_id));const html=(d.pins||[]).map(p=>`<div class="card"><b>${esc(p.nickname||'Ανακοίνωση')}</b><div>${esc(p.text||p.note||'')}</div><small>${esc(p.message_created_at||p.created_at||'')}</small></div>`).join('')||'<div class="card">Δεν υπάρχουν καρφιτσωμένα μηνύματα.</div>';panel('📌 Καρφιτσωμένα / ανακοινώσεις',html)}catch(e){panel('📌 Καρφιτσωμένα','<div class="card">Δεν φορτώθηκαν.</div>')}return false}
function toggleMessageSearch(){const p=$('ith516MessageSearch');if(!p)return false;p.classList.toggle('show');if(p.classList.contains('show'))setTimeout(()=>$('ith516MessageSearchInput')?.focus(),40);else{const q=$('ith516MessageSearchInput');if(q)q.value='';filterMessages()}return false}
function filterMessages(){const q=String($('ith516MessageSearchInput')?.value||'').trim().toLocaleLowerCase('el');document.querySelectorAll('#spaceMsgs .bubble,#spaceMsgs .card').forEach(el=>{el.style.display=!q||String(el.textContent||'').toLocaleLowerCase('el').includes(q)?'':'none'})}
function updateFollowButton(){const b=$('ith516FollowBtn');if(!b||!activeSpace)return;const on=isFollowed(activeSpace.subroom_id);b.classList.toggle('ith516FollowOn',on);b.textContent=on?'🔔 Ειδοποιήσεις ενεργές':'🔕 Ενεργοποίηση ειδοποιήσεων'}
async function toggleFollow(){if(!activeSpace)return false;const id=String(activeSpace.subroom_id);const on=!isFollowed(id);saveFollow(id,on);updateFollowButton();try{await api('/api/rooms/subscribe',{method:'POST',body:JSON.stringify({room_id:room(),subroom_id:id,device_id:device(),nickname:nickname(),enabled:on})});toast(on?'Οι ειδοποιήσεις της κοινότητας ενεργοποιήθηκαν.':'Οι ειδοποιήσεις της κοινότητας σταμάτησαν.')}catch(e){saveFollow(id,!on);updateFollowButton();toast('Δεν άλλαξαν οι ειδοποιήσεις.')}return false}
function inviteMembers(){if(!activeSpace)return false;try{const f=I().inviteToSpace||window.inviteToSpace;if(typeof f==='function')return f.call(I(),activeSpace.subroom_id)}catch(e){}return toast('Η λίστα προσκλήσεων δεν είναι διαθέσιμη.')}
async function openPolls(){if(!activeSpace)return false;panel('🗳️ Ψηφοφορίες','<div class="card">Φόρτωση…</div>');try{const d=await api('/api/rooms/polls_v249516?room_id='+encodeURIComponent(room())+'&subroom_id='+encodeURIComponent(activeSpace.subroom_id)+'&device_id='+encodeURIComponent(device()));let html=(d.polls||[]).map(p=>`<div class="card"><b>${esc(p.question)}</b>${(p.options||[]).map(o=>`<button class="btn ith516PollOption" data-poll="${esc(p.poll_id)}" data-option="${esc(o.option_id)}"><span>${esc(o.label)}</span><span>${Number(o.votes||0)}${p.my_option_id===o.option_id?' ✓':''}</span></button>`).join('')}</div>`).join('')||'<div class="card">Δεν υπάρχουν ψηφοφορίες.</div>';if(['creator','moderator'].includes(activeSpace.role))html='<button id="ith516CreatePoll" class="btn green">＋ Νέα ψηφοφορία</button>'+html;panel('🗳️ Ψηφοφορίες',html);document.querySelectorAll('[data-poll][data-option]').forEach(b=>b.addEventListener('click',async()=>{try{await api('/api/rooms/polls/vote_v249516',{method:'POST',body:JSON.stringify({room_id:room(),subroom_id:activeSpace.subroom_id,device_id:device(),poll_id:b.dataset.poll,option_id:b.dataset.option})});openPolls()}catch(e){toast(e.message)}}));$('ith516CreatePoll')?.addEventListener('click',createPoll)}catch(e){panel('🗳️ Ψηφοφορίες','<div class="card">Δεν φορτώθηκαν: '+esc(e.message)+'</div>')}return false}
async function createPoll(){const q=prompt('Ερώτηση ψηφοφορίας:')||'';if(!q)return;const raw=prompt('Επιλογές χωρισμένες με |, τουλάχιστον δύο:','Ναι | Όχι')||'';const options=raw.split('|').map(x=>x.trim()).filter(Boolean);if(options.length<2)return toast('Χρειάζονται τουλάχιστον δύο επιλογές.');const role=activeSpace.role||'creator';let code=getStaffCode(activeSpace.subroom_id,role);if(!code){code=prompt(role==='moderator'?'Κωδικός συντονιστή:':'Κωδικός δημιουργού:')||'';if(code)setStaffCode(activeSpace.subroom_id,role,code)}try{await api('/api/rooms/polls/create_v249516',{method:'POST',body:JSON.stringify({room_id:room(),subroom_id:activeSpace.subroom_id,device_id:device(),staff_code:code,question:q,options})});openPolls()}catch(e){toast(e.message)}}
async function openEvents(){if(!activeSpace)return false;panel('📅 Εκδηλώσεις','<div class="card">Φόρτωση…</div>');try{const d=await api('/api/rooms/events_v249516?room_id='+encodeURIComponent(room())+'&subroom_id='+encodeURIComponent(activeSpace.subroom_id)+'&device_id='+encodeURIComponent(device()));let html=(d.events||[]).map(e=>`<div class="card"><b>${esc(e.title)}</b><div>${esc(e.description||'')}</div><small>${new Date(Number(e.starts_at||0)*1000).toLocaleString('el-GR')} · ${esc(e.location||'')} · 👥 ${Number(e.going_count||0)}</small><div class="ith516EventActions"><button class="btn" data-event="${esc(e.event_id)}" data-rsvp="going">Θα πάω${e.my_response==='going'?' ✓':''}</button><button class="btn" data-event="${esc(e.event_id)}" data-rsvp="interested">Ενδιαφέρομαι${e.my_response==='interested'?' ✓':''}</button></div></div>`).join('')||'<div class="card">Δεν υπάρχουν εκδηλώσεις.</div>';if(['creator','moderator'].includes(activeSpace.role))html='<button id="ith516CreateEvent" class="btn green">＋ Νέα εκδήλωση</button>'+html;panel('📅 Εκδηλώσεις',html);document.querySelectorAll('[data-event][data-rsvp]').forEach(b=>b.addEventListener('click',async()=>{try{await api('/api/rooms/events/rsvp_v249516',{method:'POST',body:JSON.stringify({room_id:room(),subroom_id:activeSpace.subroom_id,device_id:device(),nickname:nickname(),event_id:b.dataset.event,response:b.dataset.rsvp})});openEvents()}catch(e){toast(e.message)}}));$('ith516CreateEvent')?.addEventListener('click',createEvent)}catch(e){panel('📅 Εκδηλώσεις','<div class="card">Δεν φορτώθηκαν: '+esc(e.message)+'</div>')}return false}
async function createEvent(){const title=prompt('Τίτλος εκδήλωσης:')||'';if(!title)return;const when=prompt('Ημερομηνία και ώρα, π.χ. 2026-08-15 20:00:')||'';const ms=Date.parse(when.replace(' ','T'));if(!Number.isFinite(ms))return toast('Η ημερομηνία δεν αναγνωρίστηκε.');const locationText=prompt('Τοποθεσία ή σύνδεσμος:')||'';const description=prompt('Περιγραφή:')||'';const role=activeSpace.role||'creator';let code=getStaffCode(activeSpace.subroom_id,role);if(!code){code=prompt(role==='moderator'?'Κωδικός συντονιστή:':'Κωδικός δημιουργού:')||'';if(code)setStaffCode(activeSpace.subroom_id,role,code)}try{await api('/api/rooms/events/create_v249516',{method:'POST',body:JSON.stringify({room_id:room(),subroom_id:activeSpace.subroom_id,device_id:device(),staff_code:code,title,description,location:locationText,starts_at:ms/1000})});openEvents()}catch(e){toast(e.message)}}
async function openManage(){if(!activeSpace)return false;let role=activeSpace.role||(_communityRoleFallback());if(!['creator','moderator'].includes(role))return toast('Η διαχείριση είναι διαθέσιμη μόνο σε δημιουργό ή συντονιστή.');let code=getStaffCode(activeSpace.subroom_id,role);if(!code){code=prompt(role==='moderator'?'Κωδικός συντονιστή:':'Κωδικός δημιουργού:')||'';if(!code)return false;setStaffCode(activeSpace.subroom_id,role,code)}panel('🛡️ Συντονισμός','<div class="card">Φόρτωση…</div>');try{const d=await api('/api/rooms/staff/panel_v249516',{method:'POST',body:JSON.stringify({room_id:room(),subroom_id:activeSpace.subroom_id,device_id:device(),staff_code:code})});activeSpace.role=d.role;let html='<div class="card"><button id="ith516EditRules" class="btn">✏️ Κανόνες / καλωσόρισμα</button></div>';html+='<div class="card"><b>Αιτήματα συμμετοχής</b>'+((d.pending||[]).map(r=>`<div class="ith516PanelRow"><span><b>${esc(r.nickname||r.device_id)}</b>${(r.answers||[]).map((a,i)=>`<div class="ith516Answer">${i+1}. ${esc(a)}</div>`).join('')}</span><div class="ith516StaffActions"><button class="btn green" data-request="${esc(r.request_id)}" data-accept="1">✓</button><button class="btn" data-request="${esc(r.request_id)}" data-accept="0">×</button></div></div>`).join('')||'<p>Δεν υπάρχουν εκκρεμή αιτήματα.</p>')+'</div>';html+='<div class="card"><b>Μέλη και ρόλοι</b>'+((d.members||[]).map(m=>`<div class="ith516PanelRow"><span><b>${esc(m.nickname||m.device_id)}</b> <span class="ith516Role">${esc(m.role||'member')}</span><small>${esc(m.device_id)}</small></span>${String(m.device_id)!==device()?`<div class="ith516StaffActions">${d.role==='creator'?`<button class="btn" data-role-target="${esc(m.device_id)}" data-role="${m.role==='moderator'?'member':'moderator'}">${m.role==='moderator'?'Αφαίρεση συντονιστή':'Κάνε συντονιστή'}</button>`:''}<button class="btn" data-block-target="${esc(m.device_id)}">⛔</button></div>`:''}</div>`).join(''))+'</div>';html+='<div class="card"><b>Ουρά αναφορών</b>'+((d.reports||[]).map(r=>`<div class="ith516PanelRow"><span>${esc(r.reason||'Αναφορά')}<small>${esc(r.message_id||'')}</small></span><div class="ith516StaffActions"><button class="btn" data-report="${esc(r.report_id)}" data-report-action="dismiss">Κλείσιμο</button><button class="btn" data-report="${esc(r.report_id)}" data-report-action="delete_message">Διαγραφή</button></div></div>`).join('')||'<p>Δεν υπάρχουν εκκρεμείς αναφορές.</p>')+'</div>';panel('🛡️ Συντονισμός · '+(d.role==='creator'?'Δημιουργός':'Συντονιστής'),html);document.querySelectorAll('[data-request]').forEach(b=>b.addEventListener('click',async()=>{try{await api('/api/rooms/staff/respond_v249516',{method:'POST',body:JSON.stringify({room_id:room(),subroom_id:activeSpace.subroom_id,device_id:device(),staff_code:code,request_id:b.dataset.request,accepted:b.dataset.accept==='1'})});openManage()}catch(e){toast(e.message)}}));document.querySelectorAll('[data-role-target]').forEach(b=>b.addEventListener('click',async()=>{try{const r=await api('/api/rooms/staff/set_role_v249516',{method:'POST',body:JSON.stringify({room_id:room(),subroom_id:activeSpace.subroom_id,device_id:device(),staff_code:code,target_id:b.dataset.roleTarget,role:b.dataset.role})});if(r.moderator_code)alert('Κωδικός συντονιστή — εμφανίζεται μία φορά:\n'+r.moderator_code);openManage()}catch(e){toast(e.message)}}));document.querySelectorAll('[data-block-target]').forEach(b=>b.addEventListener('click',async()=>{const reason=prompt('Λόγος μπλοκαρίσματος:')||'';try{await api('/api/rooms/staff/block_v249516',{method:'POST',body:JSON.stringify({room_id:room(),subroom_id:activeSpace.subroom_id,device_id:device(),staff_code:code,target_id:b.dataset.blockTarget,blocked:true,reason})});openManage()}catch(e){toast(e.message)}}));document.querySelectorAll('[data-report]').forEach(b=>b.addEventListener('click',async()=>{try{await api('/api/rooms/staff/report_action_v249516',{method:'POST',body:JSON.stringify({room_id:room(),subroom_id:activeSpace.subroom_id,device_id:device(),staff_code:code,report_id:b.dataset.report,action:b.dataset.reportAction,note:''})});openManage()}catch(e){toast(e.message)}}));$('ith516EditRules')?.addEventListener('click',async()=>{const rules=prompt('Κανόνες κοινότητας:',activeSpace.rules_text||'');if(rules===null)return;const welcome=prompt('Μήνυμα καλωσορίσματος:',activeSpace.welcome_text||'');try{await api('/api/rooms/staff/update_v249516',{method:'POST',body:JSON.stringify({room_id:room(),subroom_id:activeSpace.subroom_id,device_id:device(),staff_code:code,rules_text:rules,welcome_text:welcome||''})});activeSpace.rules_text=rules;activeSpace.welcome_text=welcome||'';toast('Οι πληροφορίες ενημερώθηκαν.');openManage()}catch(e){toast(e.message)}})}catch(e){toast('Δεν άνοιξε η διαχείριση: '+e.message,7000);try{localStorage.removeItem(staffCodeKey(activeSpace.subroom_id,role))}catch(_e){}}return false}
function _communityRoleFallback(){return activeSpace?.is_owner?'creator':'member'}
function canonical(){try{const u=new URL(location.href);if(u.searchParams.get('v')!=='249516'){u.searchParams.set('v',(window.ITHAKI_ACTIVE_VERSION||'249526r10f37f1f2'));history.replaceState(null,'',u.pathname+'?'+u.searchParams.toString()+u.hash)}}catch(e){}}
function install(){addCss();canonical();const o=I();if(!o)return;if(!o.__v249516BasePage&&typeof o.page==='function'&&!o.page.__v249516)o.__v249516BasePage=o.page;const base=o.__v249516BasePage;const pageOwner=function(id){if(String(id)==='spaces')return activateSpacesPage();return typeof base==='function'?base.apply(this,arguments):false};pageOwner.__v249516=true;Object.assign(o,{page:pageOwner,renderSpaces:renderPage,renderSpacesV249516:renderPage,activateSpacesPageV249516:activateSpacesPage,loadSpacesV249516:loadSpaces,renderSpacesListV249516:renderList,spacesKindV249516:setKind,spaceCategoryV249516:setCat,openCreateCommunityV249516:showCreate,submitCommunityV249516:submitCreate,openSpaceV249516:openSpace,closeSpaceChatV249516:closeChat,openCommunityInfoV249516:openInfo,openCommunityMembersV249516:openMembers,openCommunityPinsV249516:openPins,toggleCommunityFollowV249516:toggleFollow,openCommunityPollsV249516:openPolls,openCommunityEventsV249516:openEvents,openCommunityManagementV249516:openManage});
 try{window.renderSpaces=renderPage;window.openSpace=openSpace}catch(e){}
 if(String(S().page||'')==='spaces'||document.body?.getAttribute('data-page')==='spaces'){if(!$('ith516Shell'))renderPage();else applyView()}
 try{document.documentElement.setAttribute('data-ithaki-v249516','stable-community-open-tools');localStorage.setItem('ith_frontend_build','V249516-full-community-suite-all-files')}catch(e){}}
function installCapture(){if(window.__ITHAKI_V249516_CAPTURE_INSTALLED__)return;window.__ITHAKI_V249516_CAPTURE_INSTALLED__=true;document.addEventListener('click',e=>{try{if(newerCommunityOwner516())return;if(e.target?.closest?.('#ith516Shell'))return;const b=e.target?.closest?.('button,a,[data-page]');if(!b)return;const dp=String(b.getAttribute('data-page')||b.dataset?.page||'');const oc=String(b.getAttribute('onclick')||'');if(dp==='spaces'||/page\s*\(\s*['"]spaces['"]\s*\)/.test(oc)){e.preventDefault();e.stopImmediatePropagation();activateSpacesPage()}}catch(_e){}},true)}
function installObserver(){const page=$('spacesPage');if(!page||observer)return;observer=new MutationObserver(()=>{if(newerCommunityOwner516())return;if(rendering||document.body?.getAttribute('data-page')!=='spaces')return;if(view==='chat'||view==='create'||!$('ith516Shell')){clearTimeout(restoreTimer);restoreTimer=setTimeout(()=>{if(document.body?.getAttribute('data-page')==='spaces'&&!$('ith516Shell'))renderPage();else applyView()},35)}});observer.observe(page,{childList:true,subtree:false})}
function keepOwner(){if(newerCommunityOwner516())return;try{install();installObserver();if(document.body?.getAttribute('data-page')==='spaces'){if(!$('ith516Shell'))renderPage();else applyView()}}catch(e){}}
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',()=>{installCapture();setTimeout(keepOwner,0)},{once:true});else{installCapture();setTimeout(keepOwner,0)}
window.addEventListener('pageshow',keepOwner);window.addEventListener('popstate',keepOwner);setTimeout(keepOwner,250);setTimeout(keepOwner,900);setTimeout(keepOwner,1800);setInterval(()=>{if(document.body?.getAttribute('data-page')==='spaces')keepOwner()},3000);
})();
