/* OK ITHAKI V249434 - PROFESSIONAL ANONYMOUS WALL DIRECT OPEN / ICON ACTIONS / SAFE EXIT
   Additive frontend. Legacy wall posts remain visible; new posts and threaded
   anonymous replies use the V249375 public-wall service. */
(function () {
  "use strict";
  if (window.__ITHAKI_V411_WALL_V249431__) return;
  window.__ITHAKI_V411_WALL_V249431__ = true;

  var REACTIONS = [
    {emoji:"❤️", label:"Καρδιά"}, {emoji:"🤝", label:"Στήριξη"},
    {emoji:"🙏", label:"Σεβασμός"}, {emoji:"🌊", label:"Κύμα"},
    {emoji:"🕯️", label:"Φως"}, {emoji:"✨", label:"Ελπίδα"}
  ];
  var liveSocket = null, reconnectTimer = 0, reconnectDelay = 1800;
  var pollTimer = 0, postPollTimer = 0;
  var activeWallPost = null, activeReply = null;

  function byId(id) { return document.getElementById(id); }
  function esc(value) {
    return String(value == null ? "" : value).replace(/[&<>"']/g, function (char) {
      return ({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[char];
    });
  }
  function room() {
    try {
      var s = (window.ITH && window.ITH.state) || window.state || {};
      return String(s.room || localStorage.getItem("ithaki_room") || "ithaki-phone-test");
    } catch (_) { return "ithaki-phone-test"; }
  }
  function device() {
    try {
      var s = (window.ITH && window.ITH.state) || window.state || {};
      return String(s.device || s.device_id || localStorage.getItem("ithaki_device_id") ||
        localStorage.getItem("ithaki_device") || "");
    } catch (_) { return ""; }
  }
  function apiBase() {
    try {
      var s = (window.ITH && window.ITH.state) || window.state || {};
      return String(s.server || s.apiBase || window.ITHAKI_API_BASE || location.origin).replace(/\/$/, "");
    } catch (_) { return location.origin.replace(/\/$/, ""); }
  }
  async function request(path, options) {
    options = options || {};
    var headers = Object.assign({"Accept":"application/json"}, options.headers || {});
    if (options.body && !headers["Content-Type"]) headers["Content-Type"] = "application/json";
    var response = await fetch(apiBase() + path, Object.assign({cache:"no-store", credentials:"same-origin"}, options, {headers:headers}));
    var text = await response.text();
    var data = {};
    try { data = text ? JSON.parse(text) : {}; } catch (_) { data = {message:text}; }
    if (!response.ok || (data && data.ok === false)) {
      var error = new Error((data && (data.detail || data.note || data.message)) || ("HTTP " + response.status));
      error.status = response.status; throw error;
    }
    return data;
  }
  function toast(text) {
    try {
      if (window.toast) return window.toast(text);
      if (window.ITH && window.ITH.notifyAppEvent) return window.ITH.notifyAppEvent(text);
    } catch (_) {}
    console.log(text);
  }
  function formatTime(timestamp) {
    var value = Number(timestamp || 0); if (!value) return "τώρα";
    try { return new Date(value * 1000).toLocaleString("el-GR", {day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}); }
    catch (_) { return ""; }
  }
  function cssAttr(value) { return String(value).replace(/\\/g,"\\\\").replace(/"/g,'\\"'); }

  function injectCss() {
    if (byId("ithV411StyleV249431")) return;
    var style = document.createElement("style");
    style.id = "ithV411StyleV249431";
    style.textContent = `
      #ithV411Wall{position:fixed;inset:0;z-index:2147483645;background:radial-gradient(circle at 50% -10%,rgba(35,94,151,.30),transparent 37%),radial-gradient(circle at 0 55%,rgba(216,170,69,.14),transparent 28%),linear-gradient(155deg,#07131f 0%,#03070d 62%,#010205 100%);color:#fff;font-family:system-ui,-apple-system,"Segoe UI",sans-serif;overflow:hidden}
      #ithV411Wall *{box-sizing:border-box}.v411Shell{height:100%;display:grid;grid-template-rows:auto 1fr auto;max-width:900px;margin:0 auto}.v411Head{position:relative;padding:calc(env(safe-area-inset-top,0px) + 15px) 62px 12px 18px;border-bottom:1px solid rgba(255,217,120,.17);background:rgba(2,7,13,.64);backdrop-filter:blur(18px);-webkit-backdrop-filter:blur(18px)}
      .v411TitleLine{display:flex;align-items:center;gap:10px}.v411TitleLine .ship{width:43px;height:43px;display:grid;place-items:center;border-radius:15px;border:1px solid rgba(255,217,120,.42);background:linear-gradient(145deg,rgba(216,170,69,.19),rgba(8,19,31,.9));font-size:23px}.v411Head h1{font-size:clamp(24px,6vw,34px);margin:0;line-height:1.05}.v411Head h1 span{color:#e8ba58}.v411Head p{margin:5px 0 0;color:#bfc9d6;font-size:13px}.v411Close{position:absolute;right:12px;top:calc(env(safe-area-inset-top,0px) + 13px);width:44px;height:44px;border-radius:50%;border:1px solid rgba(255,217,120,.40);background:rgba(0,0,0,.55);color:#fff;font-size:25px;font-weight:800;display:grid;place-items:center}
      .v411LiveRow{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-top:12px}.v411LivePill,.v411SafePill{display:flex;align-items:center;gap:7px;min-height:31px;padding:0 11px;border-radius:999px;border:1px solid rgba(255,255,255,.10);background:rgba(255,255,255,.045);color:#d9e2ec;font-size:12px;font-weight:800}.v411Pulse{width:9px;height:9px;border-radius:50%;background:#65df7b;box-shadow:0 0 0 0 rgba(101,223,123,.5);animation:v411Pulse 1.8s infinite}@keyframes v411Pulse{70%{box-shadow:0 0 0 9px rgba(101,223,123,0)}100%{box-shadow:0 0 0 0 rgba(101,223,123,0)}}
      .v411Body{overflow-y:auto;-webkit-overflow-scrolling:touch;padding:14px 12px 20px}.v411List{display:grid;gap:13px}.v411Card{position:relative;border-radius:23px;padding:15px;background:linear-gradient(145deg,rgba(17,31,47,.93),rgba(5,11,18,.89));border:1px solid rgba(255,217,120,.20);box-shadow:0 17px 43px rgba(0,0,0,.28),inset 0 1px rgba(255,255,255,.04);overflow:hidden}.v411Card.v411Flash::after{content:"";position:absolute;inset:0;pointer-events:none;background:radial-gradient(circle at 80% 100%,rgba(255,217,120,.35),transparent 38%);animation:v411Flash .85s ease-out}@keyframes v411Flash{from{opacity:1}to{opacity:0}}
      .v411Meta{display:flex;align-items:center;justify-content:space-between;color:#aeb9c7;font-size:12px}.v411Anon{display:flex;align-items:center;gap:7px;color:#f5d58c;font-weight:900}.v411Anon i{font-style:normal;width:29px;height:29px;border-radius:10px;display:grid;place-items:center;background:rgba(216,170,69,.13)}.v411Text{white-space:pre-wrap;overflow-wrap:anywhere;font-size:clamp(16px,4.3vw,19px);line-height:1.47;margin:14px 1px;color:#f5f7fa}
      .v411ReactBar{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:6px;margin-top:12px}.v411React{position:relative;min-width:0;height:46px;border-radius:15px;border:1px solid rgba(255,255,255,.11);background:rgba(0,0,0,.24);color:#fff;display:flex;align-items:center;justify-content:center;gap:4px;font-size:19px;transition:transform .14s,border-color .14s,background .14s}.v411React b{font-size:11px}.v411React.is-active{border-color:rgba(255,217,120,.58);background:linear-gradient(145deg,rgba(216,170,69,.26),rgba(76,52,10,.35));box-shadow:0 8px 24px rgba(216,170,69,.11)}.v411React:active{transform:scale(.91)}.v411React.v411Pop{animation:v411Pop .42s ease-out}@keyframes v411Pop{0%{transform:scale(.72)}55%{transform:scale(1.15)}100%{transform:scale(1)}}
      .v411ActionBar{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin-top:11px}.v411Action{min-height:58px;border-radius:16px;border:1px solid rgba(255,217,120,.20);background:rgba(255,255,255,.045);color:#f5f7fa;font-weight:850;font-size:12px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:3px}.v411ActionIcon{font-size:22px;line-height:1}.v411Action strong{color:#f0ca78}.v411Action.report{width:auto;color:#9ca9b9}.v411CardFoot{display:flex;align-items:center;justify-content:space-between;margin-top:8px;color:#8f9cac;font-size:11px}.v411Empty{padding:42px 20px;text-align:center;color:#bdc8d6;border:1px dashed rgba(255,217,120,.25);border-radius:23px;background:rgba(255,255,255,.025)}
      .v411Composer{padding:10px 12px calc(env(safe-area-inset-bottom,0px) + 10px);border-top:1px solid rgba(255,217,120,.18);background:rgba(2,7,13,.86);backdrop-filter:blur(18px);-webkit-backdrop-filter:blur(18px)}.v411ComposeBox{display:grid;grid-template-columns:1fr auto;gap:9px;align-items:end}.v411ComposeBox textarea{width:100%;min-height:48px;max-height:128px;resize:none;border-radius:18px;border:1px solid rgba(255,255,255,.14);background:rgba(255,255,255,.055);color:#fff;padding:12px 13px;font:500 15px/1.35 system-ui;outline:none}.v411ComposeBox textarea:focus{border-color:rgba(255,217,120,.58)}.v411Send{width:51px;height:51px;border-radius:17px;border:0;background:linear-gradient(145deg,#d3a242,#f0cb78);color:#07101a;font-size:22px;font-weight:1000;box-shadow:0 10px 28px rgba(216,170,69,.18)}.v411ComposeMeta{display:flex;justify-content:space-between;margin:6px 3px 0;color:#8f9cac;font-size:11px}
      .v411Burst{position:fixed;z-index:2147483647;pointer-events:none;font-size:28px;animation:v411Burst .82s ease-out forwards}@keyframes v411Burst{0%{opacity:0;transform:translate(-50%,0) scale(.5)}25%{opacity:1}100%{opacity:0;transform:translate(-50%,-65px) scale(1.4)}}
      #v411CommentLayer{position:fixed;inset:0;z-index:2147483647;background:rgba(0,0,0,.63);display:flex;align-items:flex-start;justify-content:center;padding:calc(env(safe-area-inset-top,0px) + 4vh) 10px calc(env(safe-area-inset-bottom,0px) + 10px)}.v411CommentSheet{width:min(760px,100%);height:min(90dvh,900px);display:grid;grid-template-rows:auto 1fr auto;border:1px solid rgba(255,217,120,.32);border-radius:24px;background:linear-gradient(155deg,#0e1c2b,#050a11 72%);box-shadow:0 30px 90px rgba(0,0,0,.65);overflow:hidden}.v411CommentHead{display:flex;align-items:center;gap:10px;padding:12px 13px;border-bottom:1px solid rgba(255,217,120,.18);background:rgba(0,0,0,.20)}.v411CommentHead b{flex:1;font-size:17px}.v411CommentHead button{width:42px;height:42px;border-radius:14px;border:1px solid rgba(255,217,120,.24);background:rgba(255,255,255,.05);color:#fff;font-size:21px}.v411CommentList{overflow-y:auto;-webkit-overflow-scrolling:touch;padding:12px;display:grid;align-content:start;gap:9px}.v411Comment{border:1px solid rgba(255,255,255,.10);border-radius:17px;background:rgba(255,255,255,.045);padding:11px}.v411Comment.isReply{margin-left:34px;border-left:3px solid rgba(232,186,88,.55)}.v411CommentTop{display:flex;justify-content:space-between;gap:8px;color:#9eabb9;font-size:11px}.v411CommentTop b{color:#f0cd82}.v411CommentText{white-space:pre-wrap;overflow-wrap:anywhere;line-height:1.42;margin:7px 0 5px}.v411ReplyBtn{border:0;background:transparent;color:#efc86f;font-weight:850;padding:5px 0}.v411ReplyContext{display:none;margin:0 12px 8px;padding:9px 11px;border-radius:13px;background:rgba(216,170,69,.12);border:1px solid rgba(216,170,69,.24);font-size:12px;color:#e9d4a1}.v411ReplyContext.show{display:flex;align-items:center;gap:8px}.v411ReplyContext span{flex:1}.v411ReplyContext button{border:0;background:transparent;color:#fff;font-size:18px}.v411CommentComposer{padding:10px 12px calc(env(safe-area-inset-bottom,0px) + 9px);border-top:1px solid rgba(255,217,120,.17);background:rgba(1,5,9,.86)}.v411CommentComposeRow{display:grid;grid-template-columns:1fr auto;gap:8px}.v411CommentComposeRow textarea{min-height:50px;max-height:120px;resize:none;border-radius:16px;border:1px solid rgba(255,255,255,.14);background:rgba(255,255,255,.055);color:#fff;padding:12px;font:500 15px/1.35 system-ui}.v411CommentComposeRow button{width:52px;border:0;border-radius:16px;background:linear-gradient(145deg,#d3a242,#f0cb78);color:#07101a;font-size:22px}.v411CommentNote{font-size:11px;color:#8997a8;margin-top:6px}
      @media(max-width:520px){.v411SafePill{display:none}.v411ReactBar{gap:4px}.v411React{height:43px;font-size:17px}.v411Action{font-size:12px}.v411CommentSheet{height:94dvh;border-radius:21px}.v411CommentList{padding-bottom:18px}}
    `;
    document.head.appendChild(style);
  }

  function normalizePosts(data, source) {
    var list = (data && (data.posts || data.items || data.wall)) || [];
    if (!Array.isArray(list)) return [];
    return list.map(function (post, index) {
      return {
        post_id:String(post.post_id || post.id || post.wall_id || (source + "_" + index)),
        text:String(post.text || post.message || post.body || ""),
        created_at:Number(post.created_at || post.timestamp || 0),
        comments:Number(post.comments || post.comment_count || 0),
        source:source || "legacy"
      };
    }).filter(function (post) { return post.post_id && post.text; });
  }
  async function loadWallData() {
    var all = [], seen = Object.create(null);
    try {
      var modern = await request("/api/wall/v249375/list?room_id=" + encodeURIComponent(room()) + "&owner_token=" + encodeURIComponent(device()) + "&limit=100");
      all = all.concat(normalizePosts(modern, "v249375"));
      if (modern.online != null) updateLive(modern.online);
    } catch (_) {}
    var endpoints = ["/api/wall/list_v249344", "/api/wall/list_v249339", "/api/wall/list"];
    for (var i=0;i<endpoints.length;i++) {
      try {
        var legacy = await request(endpoints[i] + "?room_id=" + encodeURIComponent(room()) + "&limit=100");
        all = all.concat(normalizePosts(legacy, "legacy")); break;
      } catch (_) {}
    }
    all = all.filter(function (post) {
      var key = post.post_id || (post.text + "|" + post.created_at);
      if (seen[key]) return false; seen[key] = true; return true;
    });
    all.sort(function (a,b) { return Number(b.created_at||0)-Number(a.created_at||0); });
    return all.slice(0,140);
  }
  function reactionButtons(postId) {
    return REACTIONS.map(function (r) {
      return '<button type="button" class="v411React" data-v411-emoji="'+esc(r.emoji)+'" data-v411-post="'+esc(postId)+'" title="'+esc(r.label)+'"><span>'+r.emoji+'</span><b>0</b></button>';
    }).join("");
  }
  function cardHtml(post) {
    return '<article class="v411Card" data-v411-card="'+esc(post.post_id)+'" data-v411-text="'+esc(post.text)+'">'+
      '<div class="v411Meta"><span class="v411Anon"><i>🎭</i> Ανώνυμος</span><span>'+esc(formatTime(post.created_at))+'</span></div>'+
      '<div class="v411Text">'+esc(post.text)+'</div><div class="v411ReactBar">'+reactionButtons(post.post_id)+'</div>'+
      '<div class="v411ActionBar">'+
        '<button type="button" class="v411Action" data-v411-comments="'+esc(post.post_id)+'"><span class="v411ActionIcon">💬</span><span>Σχόλια <strong data-v411-comment-count="'+esc(post.post_id)+'">'+Number(post.comments||0)+'</strong></span></button>'+
        '<button type="button" class="v411Action" data-v411-answer="'+esc(post.post_id)+'"><span class="v411ActionIcon">✉️</span><span>Απάντηση</span></button>'+
        '<button type="button" class="v411Action report" data-v411-report="'+esc(post.post_id)+'" title="Αναφορά"><span class="v411ActionIcon">⚑</span><span>Αναφορά</span></button>'+
      '</div><div class="v411CardFoot"><span>Ανώνυμες απαντήσεις με νήμα</span><span>ΙΘΑΚΗ</span></div></article>';
  }
  async function renderWall(keepPosition) {
    var body=byId("v411Body"), list=byId("v411List"); if(!body||!list)return;
    var top=keepPosition?body.scrollTop:0;
    try {
      var posts=await loadWallData();
      list.innerHTML=posts.length?posts.map(cardHtml).join(""):'<div class="v411Empty"><div style="font-size:38px;margin-bottom:10px">🧱</div><b>Ο Τοίχος περιμένει την πρώτη σκέψη.</b><br><span>Γράψε ανώνυμα και με σεβασμό.</span></div>';
      if(keepPosition)body.scrollTop=top;
      await hydrateReactions(posts.map(function(p){return p.post_id;}));
    } catch(error) { list.innerHTML='<div class="v411Empty"><b>Ο Τοίχος δεν φορτώθηκε.</b><br><span>'+esc(error.message||"Σφάλμα σύνδεσης")+'</span></div>'; }
  }
  function updateLive(value){var n=byId("v411LiveCount");if(n)n.textContent=String(Math.max(0,Number(value||0)));}
  function applyReactionState(item, animateEmoji) {
    if(!item||!item.post_id)return; var card=document.querySelector('[data-v411-card="'+cssAttr(item.post_id)+'"]'); if(!card)return;
    var counts=item.counts||{}, mine=item.mine||null;
    Array.prototype.forEach.call(card.querySelectorAll("[data-v411-emoji]"),function(button){var emoji=button.getAttribute("data-v411-emoji"),count=button.querySelector("b");if(count)count.textContent=String(Number(counts[emoji]||0));if(mine)button.classList.toggle("is-active",mine.indexOf(emoji)>=0);if(animateEmoji&&emoji===animateEmoji){button.classList.remove("v411Pop");void button.offsetWidth;button.classList.add("v411Pop");}});
    if(animateEmoji){card.classList.remove("v411Flash");void card.offsetWidth;card.classList.add("v411Flash");}
  }
  async function hydrateReactions(postIds){postIds=(postIds||[]).slice(0,120);if(!postIds.length)return;try{var data=await request("/api/v411/wall/reactions?room_id="+encodeURIComponent(room())+"&post_ids="+encodeURIComponent(postIds.join(","))+"&device_id="+encodeURIComponent(device()));updateLive(data.live_now);(data.items||[]).forEach(function(item){applyReactionState(item);});}catch(_){} }
  function burst(button,emoji){try{var rect=button.getBoundingClientRect(),node=document.createElement("div");node.className="v411Burst";node.textContent=emoji;node.style.left=(rect.left+rect.width/2)+"px";node.style.top=(rect.top+4)+"px";document.body.appendChild(node);setTimeout(function(){node.remove();},900);}catch(_){} }
  async function toggleReaction(button){var postId=button.getAttribute("data-v411-post"),emoji=button.getAttribute("data-v411-emoji");if(!postId||!emoji||button.disabled)return;button.disabled=true;burst(button,emoji);try{var result=await request("/api/v411/wall/reaction",{method:"POST",body:JSON.stringify({room_id:room(),post_id:postId,device_id:device(),emoji:emoji})});applyReactionState(result,emoji);updateLive(result.live_now);}catch(error){if(error.status!==429)toast("Η αντίδραση δεν καταχωρήθηκε.");}finally{setTimeout(function(){button.disabled=false;},260);} }

  async function sendWallPost(){var field=byId("v411Text"),button=byId("v411Send");if(!field||!button)return;var text=field.value.trim();if(!text)return toast("Γράψε πρώτα τη σκέψη σου.");if(text.length>500)return toast("Το κείμενο είναι πάνω από 500 χαρακτήρες.");button.disabled=true;var payload=JSON.stringify({room_id:room(),owner_token:device(),text:text}),sent=false,lastError=null;
    var endpoints=["/api/wall/v249375/post","/api/wall/post_v249344","/api/wall/post_v249339","/api/wall/post"];
    for(var i=0;i<endpoints.length;i++){try{await request(endpoints[i],{method:"POST",body:payload});sent=true;break;}catch(error){lastError=error;}}
    if(sent){field.value="";updateCounter();await renderWall(false);var body=byId("v411Body");if(body)body.scrollTop=0;}else toast("Δεν στάλθηκε: "+((lastError&&lastError.message)||"σφάλμα"));button.disabled=false;
  }
  async function reportPost(postId){if(!postId)return;var endpoints=[{path:"/api/wall/v249375/report",body:{post_id:postId,owner_token:device(),reason:"user_report"}},{path:"/api/wall/report_v249344",body:{room_id:room(),owner_token:device(),post_id:postId,reason:"user_report"}},{path:"/api/report",body:{room_id:room(),reporter_id:device(),target_type:"wall",target_id:postId,reason:"user_report"}}];for(var i=0;i<endpoints.length;i++){try{await request(endpoints[i].path,{method:"POST",body:JSON.stringify(endpoints[i].body)});return toast("Η αναφορά καταχωρήθηκε.");}catch(_){} }toast("Η αναφορά δεν καταχωρήθηκε.");}
  function updateCounter(){var f=byId("v411Text"),c=byId("v411Counter");if(f&&c)c.textContent=String(f.value.length)+"/500";}

  function commentLayerMarkup(post){return '<section id="v411CommentLayer" role="dialog" aria-modal="true"><div class="v411CommentSheet"><header class="v411CommentHead"><button type="button" id="v411CommentBack" aria-label="Πίσω">←</button><b>💬 Ανώνυμες απαντήσεις</b><button type="button" id="v411CommentClose" aria-label="Κλείσιμο">×</button></header><main class="v411CommentList" id="v411CommentList"><div class="v411Empty">Φόρτωση απαντήσεων…</div></main><footer class="v411CommentComposer"><div class="v411ReplyContext" id="v411ReplyContext"><span id="v411ReplyLabel"></span><button type="button" id="v411ReplyClear">×</button></div><div class="v411CommentComposeRow"><textarea id="v411CommentText" maxlength="1500" placeholder="Γράψε ανώνυμη απάντηση…"></textarea><button type="button" id="v411CommentSend">➤</button></div><div class="v411CommentNote">Η απάντηση παραμένει ανώνυμη και εμφανίζεται μέσα στο νήμα της δημοσίευσης.</div></footer></div></section>';}
  function closeComments(){var n=byId("v411CommentLayer");if(n)n.remove();activeWallPost=null;activeReply=null;}
  function setReply(commentId,number,text){activeReply={comment_id:String(commentId||""),number:Number(number||0),text:String(text||"")};var box=byId("v411ReplyContext"),label=byId("v411ReplyLabel");if(box)box.classList.add("show");if(label)label.textContent="↩ Απάντηση στο #"+activeReply.number+": "+activeReply.text.slice(0,80);var field=byId("v411CommentText");if(field){field.placeholder="Απάντηση στο #"+activeReply.number+"…";field.focus();}}
  function clearReply(){activeReply=null;var box=byId("v411ReplyContext"),field=byId("v411CommentText");if(box)box.classList.remove("show");if(field)field.placeholder="Γράψε ανώνυμη απάντηση…";}
  function commentsHtml(items){items=Array.isArray(items)?items:[];if(!items.length)return '<div class="v411Empty">Δεν υπάρχουν ακόμη απαντήσεις.<br>Γίνε η πρώτη ανώνυμη φωνή.</div>';var numberById={};items.forEach(function(x,i){numberById[String(x.comment_id||"")]=i+1;});return items.map(function(item,index){var id=String(item.comment_id||""),parent=String(item.parent_id||""),num=index+1,parentNum=numberById[parent]||0;return '<article class="v411Comment '+(parent?'isReply':'')+'" data-v411-comment-id="'+esc(id)+'"><div class="v411CommentTop"><b>#'+num+' '+(parentNum?'· απάντηση στο #'+parentNum:'· Ανώνυμος')+'</b><span>'+esc(formatTime(item.created_at))+'</span></div><div class="v411CommentText">'+esc(item.text||"")+'</div><button type="button" class="v411ReplyBtn" data-v411-reply="'+esc(id)+'" data-v411-reply-number="'+num+'" data-v411-reply-text="'+esc(item.text||"")+'">↩ Απάντηση</button></article>';}).join("");}
  async function loadComments(){if(!activeWallPost)return;var list=byId("v411CommentList");if(!list)return;try{var data=await request("/api/wall/v249375/comments?post_id="+encodeURIComponent(activeWallPost.post_id)+"&owner_token="+encodeURIComponent(device())+"&limit=300");var items=data.items||[];list.innerHTML=commentsHtml(items);var counter=document.querySelector('[data-v411-comment-count="'+cssAttr(activeWallPost.post_id)+'"]');if(counter)counter.textContent=String(items.length);requestAnimationFrame(function(){list.scrollTop=list.scrollHeight;});}catch(error){list.innerHTML='<div class="v411Empty">Οι απαντήσεις δεν φορτώθηκαν.<br>'+esc(error.message||"")+'</div>';}}
  async function sendComment(){if(!activeWallPost)return;var field=byId("v411CommentText"),button=byId("v411CommentSend");if(!field||!button)return;var text=field.value.trim();if(!text)return toast("Γράψε πρώτα την απάντησή σου.");button.disabled=true;try{await request("/api/wall/v249375/comment",{method:"POST",body:JSON.stringify({post_id:activeWallPost.post_id,owner_token:device(),text:text,parent_id:activeReply&&activeReply.comment_id||"",room_id:room()})});field.value="";clearReply();await loadComments();}catch(error){toast("Δεν στάλθηκε η απάντηση: "+(error.message||"σφάλμα"));}button.disabled=false;}
  function openComments(postId,focusComposer){var card=document.querySelector('[data-v411-card="'+cssAttr(postId)+'"]');activeWallPost={post_id:String(postId),text:card?String(card.getAttribute("data-v411-text")||""):""};activeReply=null;var old=byId("v411CommentLayer");if(old)old.remove();document.body.insertAdjacentHTML("beforeend",commentLayerMarkup(activeWallPost));byId("v411CommentBack").onclick=closeComments;byId("v411CommentClose").onclick=closeComments;byId("v411ReplyClear").onclick=clearReply;byId("v411CommentSend").onclick=sendComment;byId("v411CommentText").addEventListener("keydown",function(event){if((event.ctrlKey||event.metaKey)&&event.key==="Enter")sendComment();});byId("v411CommentList").addEventListener("click",function(event){var b=event.target.closest("[data-v411-reply]");if(b)setReply(b.getAttribute("data-v411-reply"),b.getAttribute("data-v411-reply-number"),b.getAttribute("data-v411-reply-text"));});loadComments().then(function(){if(focusComposer){var f=byId("v411CommentText");if(f)f.focus();}});return false;}

  function socketUrl(){return apiBase().replace(/^http:/,"ws:").replace(/^https:/,"wss:")+"/ws/v411/wall/"+encodeURIComponent(room())+"?device_id="+encodeURIComponent(device());}
  function connectLive(){if(!byId("ithV411Wall"))return;try{if(liveSocket)liveSocket.close();}catch(_){}try{liveSocket=new WebSocket(socketUrl());liveSocket.onopen=function(){reconnectDelay=1800;};liveSocket.onmessage=function(event){var message=null;try{message=JSON.parse(event.data);}catch(_){return;}if(message.type==="v411_hello"||message.type==="v411_presence")updateLive(message.live_now);else if(message.type==="v411_reaction")applyReactionState({post_id:message.post_id,counts:message.counts},message.emoji);};liveSocket.onclose=function(){liveSocket=null;if(!byId("ithV411Wall"))return;clearTimeout(reconnectTimer);reconnectTimer=setTimeout(connectLive,reconnectDelay);reconnectDelay=Math.min(20000,Math.round(reconnectDelay*1.65));};liveSocket.onerror=function(){try{liveSocket.close();}catch(_){}};}catch(_){} }
  function closeWall(silent){closeComments();var modal=byId("ithV411Wall");if(modal)modal.remove();clearTimeout(reconnectTimer);clearInterval(pollTimer);clearInterval(postPollTimer);try{if(liveSocket)liveSocket.close();}catch(_){}liveSocket=null;if(!silent){try{if(window.ITH&&typeof ITH.stableRouteV249429==="function")ITH.stableRouteV249429("home","wall-exit-v249434");else if(window.ITH&&typeof ITH.page==="function")ITH.page("home");}catch(_){}}}
  function wallMarkup(){return '<div class="v411Shell"><header class="v411Head"><button type="button" class="v411Close" id="v411Close" aria-label="Έξοδος">‹</button><div class="v411TitleLine"><div class="ship">⛵</div><div><h1>Ανώνυμος <span>Τοίχος</span></h1><p>Σχόλια, απαντήσεις και ανθρώπινη επικοινωνία χωρίς εμφάνιση ταυτότητας.</p></div></div><div class="v411LiveRow"><div class="v411LivePill"><i class="v411Pulse"></i> Ζωντανά τώρα: <b id="v411LiveCount">0</b></div><div class="v411SafePill">🛡️ Χωρίς εμφάνιση ταυτότητας</div></div></header><main class="v411Body" id="v411Body"><div class="v411List" id="v411List"><div class="v411Empty">Φόρτωση Τοίχου…</div></div></main><footer class="v411Composer"><div class="v411ComposeBox"><textarea id="v411Text" maxlength="500" placeholder="Γράψε ανώνυμα τη σκέψη σου…"></textarea><button type="button" class="v411Send" id="v411Send">➤</button></div><div class="v411ComposeMeta"><span>Με σεβασμό στους άλλους</span><span id="v411Counter">0/500</span></div></footer></div>';}
  function openWall(){injectCss();closeWall(true);var modal=document.createElement("section");modal.id="ithV411Wall";modal.setAttribute("role","dialog");modal.setAttribute("aria-modal","true");modal.innerHTML=wallMarkup();document.body.appendChild(modal);byId("v411Close").onclick=function(){closeWall(false)};byId("v411Send").onclick=sendWallPost;byId("v411Text").addEventListener("input",updateCounter);byId("v411Text").addEventListener("keydown",function(event){if((event.ctrlKey||event.metaKey)&&event.key==="Enter")sendWallPost();});byId("v411List").addEventListener("click",function(event){var reaction=event.target.closest("[data-v411-emoji]");if(reaction)return toggleReaction(reaction);var comments=event.target.closest("[data-v411-comments]");if(comments)return openComments(comments.getAttribute("data-v411-comments"),false);var answer=event.target.closest("[data-v411-answer]");if(answer)return openComments(answer.getAttribute("data-v411-answer"),true);var report=event.target.closest("[data-v411-report]");if(report)return reportPost(report.getAttribute("data-v411-report"));});renderWall(false);connectLive();pollTimer=setInterval(function(){var ids=Array.prototype.map.call(document.querySelectorAll("[data-v411-card]"),function(card){return card.getAttribute("data-v411-card");});hydrateReactions(ids);},12000);postPollTimer=setInterval(function(){if(!byId("v411CommentLayer"))renderWall(true);},25000);return false;}

  window.openWallV411=openWall;window.openAnonymousWallV411=openWall;window.openWall=openWall;window.openAnonymousWall=openWall;window.openWallCommentsV249431=openComments;window.closeWallCommentsV249431=closeComments;window.closeWallV249434=function(){closeWall(false)};window.closeWallSilentV249496=function(){closeWall(true)};
  window.ITH=window.ITH||{};window.ITH.openWallV411=openWall;window.ITH.openAnonymousWallV411=openWall;window.ITH.openWallV249344=openWall;window.ITH.openAnonymousWallV249344=openWall;window.ITH.openWallV249339=openWall;window.ITH.openWallCommentsV249431=openComments;window.ITH.closeWallV249434=function(){closeWall(false)};window.ITH.closeWallSilentV249496=function(){closeWall(true)};
  document.addEventListener("click",function(event){var target=event.target&&event.target.closest?event.target.closest("button,a,[role='button']"):null;if(!target||target.closest("#ithV411Wall")||target.closest("#v411CommentLayer"))return;var idClassAction=[target.id||"",target.className||"",target.getAttribute("data-action")||"",target.getAttribute("data-feature")||""].join(" ").toLowerCase();var text=String(target.textContent||"").trim().toLowerCase();var isWallAction=/(^|[\s_-])(anonymous-?wall|open-?wall|wall)([\s_-]|$)/.test(idClassAction)||text==="τοίχος"||text==="ανώνυμος τοίχος"||text==="wall"||text==="anonymous wall";if(isWallAction&&idClassAction.indexOf("firewall")<0){event.preventDefault();event.stopPropagation();openWall();}},true);
})();
