/* OK ITHAKI V249470
 * Mobile video canonical URL repair, gentle Bil, nickname-only onboarding,
 * and avatar-name in-app notices for messages, friend requests, likes and followers.
 * Database/media/messages/calls/friends are not deleted or migrated.
 */
(function(){
  'use strict';
  if(window.__ITHAKI_V249470_MOBILE_COMPLETE__) return;
  window.__ITHAKI_V249470_MOBILE_COMPLETE__={version:'V249470',installedAt:Date.now()};

  var CANONICAL='https://ok-ithaki.gr';
  var BIL_ID='ithBilGreenTurtleV249461';
  var BIL_POP_ID='ithBilPopV249461';
  var ONBOARD_ID='ithBilNicknameOnboardingV249470';
  var NOTICE_SEEN_KEY='ith_v249470_notice_seen';
  var MEDIA_RETRY='data-ith-v249470-media-retry';
  var WISDOM_VISIBLE_MS=15000;
  var monitorTimer=0;
  var mediaObserver=null;
  var lastAlertAt=0;

  function I(){return window.ITH||(window.ITH={});}
  function S(){return window.state||window.__ITHAKI_CORE_STATE__||(I().state||{});}
  function esc(v){return String(v==null?'':v).replace(/[&<>"']/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]});}
  function english(){try{return String(localStorage.getItem('ith_ui_lang_v249141')||localStorage.getItem('ith_ui_lang')||document.documentElement.lang||'el').toLowerCase().indexOf('en')===0}catch(e){return false}}
  function tr(el,en){return english()?en:el;}
  function isAssetPage(){return location.protocol==='file:'||location.hostname==='appassets.androidplatform.net';}
  function apiBase(){
    var s=S(),b=String(s.api||window.ITHAKI_API_BASE||CANONICAL).replace(/\/+$/,'');
    if(!b||/appassets\.androidplatform\.net/i.test(b)||/^file:/i.test(b)) b=CANONICAL;
    return b;
  }
  function forceCanonicalState(){
    if(!isAssetPage()) return;
    try{S().api=CANONICAL;}catch(e){}
    try{window.ITHAKI_API_BASE=CANONICAL;window.__ITHAKI_CANONICAL_API_BASE_V249470__=CANONICAL;}catch(e){}
    try{localStorage.setItem('ith_api_base',CANONICAL);localStorage.removeItem('ith_saved_api_base');localStorage.removeItem('ith_server_base');}catch(e){}
    try{document.documentElement.setAttribute('data-v249470-canonical-api',CANONICAL);}catch(e){}
  }
  function canonicalMedia(raw){
    var v=String(raw||'').trim(); if(!v) return v;
    try{
      var u=new URL(v,location.href);
      if(/^\/api\/media\/file\//.test(u.pathname)) return CANONICAL+u.pathname+u.search+u.hash;
      if(isAssetPage()&&u.hostname==='appassets.androidplatform.net'&&/^\/api\//.test(u.pathname)) return CANONICAL+u.pathname+u.search+u.hash;
    }catch(e){if(/^\/api\/media\/file\//.test(v))return CANONICAL+v;}
    return v;
  }
  function patchMediaElement(el){
    if(!el||!el.getAttribute)return;
    var tag=String(el.tagName||'').toLowerCase();
    var attr=(tag==='a')?'href':'src';
    var raw=el.getAttribute(attr)||'';
    var fixed=canonicalMedia(raw);
    if(fixed&&fixed!==raw){
      el.setAttribute(attr,fixed);
      if(tag==='video'||tag==='audio'){try{el.load();}catch(e){}}
    }
    if(tag==='video'){
      el.setAttribute('playsinline','');el.setAttribute('webkit-playsinline','');
      if(!el.getAttribute('preload'))el.setAttribute('preload','metadata');
      if(!el.__ithV249470Error){
        el.__ithV249470Error=true;
        el.addEventListener('error',function(){
          try{
            if(el.getAttribute(MEDIA_RETRY)==='1')return;
            el.setAttribute(MEDIA_RETRY,'1');
            var src=canonicalMedia(el.currentSrc||el.getAttribute('src')||'');
            if(src){src+=(src.indexOf('?')>=0?'&':'?')+'ith_v=249470';el.setAttribute('src',src);el.load();}
          }catch(e){}
        },{passive:true});
      }
    }
  }
  function fixAllMedia(root){
    forceCanonicalState();
    root=root||document;
    try{if(root.matches&&root.matches('video,audio,source,img,a[href*="/api/media/file/"]'))patchMediaElement(root);}catch(e){}
    try{root.querySelectorAll&&root.querySelectorAll('video,audio,source,img,a[href*="/api/media/file/"]').forEach(patchMediaElement);}catch(e){}
  }

  function addCss(){
    if(document.getElementById('ithV249470Css'))return;
    var st=document.createElement('style');st.id='ithV249470Css';st.textContent=`
      #${BIL_ID} .bilFace467,#${BIL_ID} .sokraMiniV249252,#${BIL_ID} .bilAliveV249466{animation:none!important;transform:none!important}
      #${BIL_ID} .bilShell467,#${BIL_ID} .shell,#${BIL_ID} .bilFoot467,#${BIL_ID} .foot{animation:none!important;transform:none!important}
      #${BIL_ID} .bilHead467,#${BIL_ID} .head{animation:ithBilHeadGentleV249470 6.8s ease-in-out infinite!important;transform-origin:50% 105%!important}
      #${BIL_ID} .bilEye467,#${BIL_ID} .eye{animation:ithBilBlinkGentleV249470 7.2s ease-in-out infinite!important}
      @keyframes ithBilHeadGentleV249470{0%,100%{transform:rotate(-1deg)}50%{transform:rotate(2deg)}}
      @keyframes ithBilBlinkGentleV249470{0%,47%,51%,100%{transform:scaleY(1)}49%{transform:scaleY(.18)}}
      #${ONBOARD_ID}{position:fixed;inset:0;z-index:2147483646;display:grid;place-items:center;padding:18px;background:rgba(1,8,15,.76);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px)}
      #${ONBOARD_ID} .ithOnboardCard470{width:min(430px,100%);border-radius:26px;padding:20px;background:linear-gradient(160deg,#071a28,#0a2534);color:#fff;border:1px solid rgba(255,255,255,.18);box-shadow:0 30px 90px rgba(0,0,0,.58)}
      #${ONBOARD_ID} .ithOnboardTop470{display:flex;align-items:center;gap:12px;margin-bottom:12px}#${ONBOARD_ID} .ithOnboardTop470 b{font-size:22px}#${ONBOARD_ID} .ithOnboardTop470 span{font-size:38px}
      #${ONBOARD_ID} p{line-height:1.55;color:rgba(255,255,255,.82)}#${ONBOARD_ID} input{width:100%;box-sizing:border-box;min-height:50px;border-radius:15px;padding:10px 13px;background:#fff;color:#07131f;border:2px solid rgba(255,217,110,.75);font-size:18px;font-weight:800}
      #${ONBOARD_ID} .ithOnboardActions470{display:grid;grid-template-columns:1fr auto;gap:9px;margin-top:12px}#${ONBOARD_ID} button{min-height:46px;border-radius:14px;border:0;padding:9px 13px;font-weight:900;cursor:pointer}#${ONBOARD_ID} .save{background:#1a9b50;color:#fff}#${ONBOARD_ID} .later{background:rgba(255,255,255,.12);color:#fff}
      #${ONBOARD_ID} .status{min-height:20px;margin-top:9px;color:#ffd96e;font-size:13px;font-weight:800}
      #feedPage video.feedVideo{background:#000!important;object-fit:contain!important}
    `;document.head.appendChild(st);
  }

  function bilVisible(){var h=document.getElementById('homePage');return !!(!document.body||!document.body.dataset.page||document.body.dataset.page==='home'||(h&&h.classList.contains('active')));}
  function showBil(text,action){
    if(!document.body)return false;
    var old=document.getElementById(BIL_POP_ID);if(old)old.remove();
    var d=document.createElement(action?'button':'div');d.id=BIL_POP_ID;if(action)d.type='button';
    d.innerHTML='<span>'+esc(text)+'</span>';if(action){d.style.cursor='pointer';d.onclick=function(){try{d.remove()}catch(e){};try{action()}catch(e){}};}
    document.body.appendChild(d);requestAnimationFrame(function(){d.classList.add('show')});
    setTimeout(function(){if(d.isConnected){d.classList.remove('show');setTimeout(function(){if(d.isConnected)d.remove()},220);}},WISDOM_VISIBLE_MS);
    return true;
  }
  function nicknameInfo(){
    var s=S(),n='';try{n=String(localStorage.getItem('ith_name')||'').trim()}catch(e){}if(!n)n=String(s.name||s.nickname||'').trim();
    var fresh=!n||/^(Μέλος(?:\d+)?|Member(?:\d+)?|Guest|Επισκέπτης|Visitor|Ανώνυμος|Anonymous)$/i.test(n);
    return {fresh:fresh,name:fresh?tr('φίλε','friend'):n};
  }
  function greet(){
    try{if(sessionStorage.getItem('ith_v249470_greeted')==='1')return;sessionStorage.setItem('ith_v249470_greeted','1');}catch(e){}
    var n=nicknameInfo();
    setTimeout(function(){
      showBil(n.fresh?tr('Γεια σου! Στην ΙΘΑΚΗ χρειάζεσαι μόνο ένα ψευδώνυμο.','Hello! ITHAKI needs only a nickname.'):tr('Γεια σου '+n.name+'! Χαίρομαι που σε βλέπω ξανά.','Hello '+n.name+'! It is good to see you again.'));
      if(n.fresh)setTimeout(showOnboarding,900);
    },1300);
  }
  function showOnboarding(){
    if(window.__ITHAKI_R10F9_CLASSIC_ENTRY_OWNER__)return false;
    if(!document.body||document.getElementById(ONBOARD_ID)||!nicknameInfo().fresh)return false;
    var d=document.createElement('section');d.id=ONBOARD_ID;d.setAttribute('role','dialog');d.setAttribute('aria-modal','true');
    d.innerHTML='<div class="ithOnboardCard470"><div class="ithOnboardTop470"><span>🐢</span><div><b>'+tr('Καλώς ήρθες στην ΙΘΑΚΗ','Welcome to ITHAKI')+'</b><div>Bil</div></div></div><p>'+tr('Η εγγραφή γίνεται μόνο με ψευδώνυμο — χωρίς email και χωρίς τηλέφωνο. Με την εγγραφή επιβεβαιώνεις ότι είσαι 18+ και αποδέχεσαι τους κανόνες καθαρής επικοινωνίας.','Registration uses only a nickname — no email and no phone number. By registering you confirm that you are 18+ and accept the clean-communication rules.')+'</p><input id="ithNicknameInput470" maxlength="40" autocomplete="nickname" placeholder="'+tr('Γράψε ψευδώνυμο','Enter a nickname')+'"><div class="ithOnboardActions470"><button class="save" data-save>'+tr('Εγγραφή με ψευδώνυμο','Register with nickname')+'</button><button class="later" data-later>'+tr('Αργότερα','Later')+'</button></div><div class="status" id="ithNicknameStatus470"></div></div>';
    d.querySelector('[data-later]').onclick=function(){d.remove();};d.querySelector('[data-save]').onclick=saveNickname;
    d.querySelector('input').addEventListener('keydown',function(e){if(e.key==='Enter')saveNickname();});document.body.appendChild(d);setTimeout(function(){try{d.querySelector('input').focus()}catch(e){}},120);return false;
  }
  async function saveNickname(){
    var d=document.getElementById(ONBOARD_ID),input=document.getElementById('ithNicknameInput470'),status=document.getElementById('ithNicknameStatus470');if(!d||!input)return;
    var n=String(input.value||'').trim();if(n.length<2||n.length>40){if(status)status.textContent=tr('Το ψευδώνυμο πρέπει να έχει 2–40 χαρακτήρες.','Nickname must contain 2–40 characters.');return;}
    if(status)status.textContent=tr('Έλεγχος ψευδωνύμου…','Checking nickname…');
    var s=S(),room=String(s.room||localStorage.getItem('ith_room')||'ithaki-phone-test'),device=String(s.device||localStorage.getItem('ith_device')||'');
    try{
      var ck=await fetch(apiBase()+'/api/profile/check?room_id='+encodeURIComponent(room)+'&nickname='+encodeURIComponent(n)+'&device_id='+encodeURIComponent(device),{cache:'no-store'});var cj=await ck.json();
      if(!cj.available){if(status)status.textContent=cj.message||tr('Το ψευδώνυμο χρησιμοποιείται ήδη.','Nickname is already used.');return;}
      try{localStorage.setItem('ith_name',n);localStorage.setItem('ith_age16','1');localStorage.setItem('ith_policy_ok','1');localStorage.setItem('ith_registered_member_v249154','1');}catch(e){}
      s.name=n;s.nickname=n;s.age16=true;s.policyOk=true;
      var r=await fetch(apiBase()+'/api/profile/register',{method:'POST',headers:{'Content-Type':'application/json','X-ITHAKI-TOKEN':String(s.token||'OKITHAKI_PUBLIC_BETA_TOKEN_SERVER_ONLY_2026')},body:JSON.stringify({room_id:room,device_id:device,nickname:n,language:english()?'en':'el',adult_confirmed:true,policy_accepted:true,ai_host_enabled:false})});
      if(!r.ok)throw new Error('HTTP '+r.status);
      d.remove();showBil(tr('Χαίρομαι που σε γνωρίζω, '+n+'. Η εγγραφή ολοκληρώθηκε μόνο με το ψευδώνυμό σου.','Nice to meet you, '+n+'. Registration is complete using only your nickname.'));
      try{if(typeof I().renderProfile==='function')I().renderProfile();if(typeof I().loadPeople==='function')I().loadPeople();}catch(e){}
    }catch(e){
      /* Keep the nickname locally and retry normal sync later; do not lose the user's choice. */
      try{localStorage.setItem('ith_name',n);localStorage.setItem('ith_age16','1');localStorage.setItem('ith_policy_ok','1');localStorage.setItem('ith_profile_name_pending_sync','1');}catch(_e){}
      s.name=n;s.nickname=n;s.age16=true;s.policyOk=true;if(status)status.textContent=tr('Το ψευδώνυμο αποθηκεύτηκε στη συσκευή. Θα συγχρονιστεί όταν απαντήσει ο server.','Nickname was saved on the device and will sync when the server responds.');setTimeout(function(){try{d.remove();showBil(tr('Γεια σου '+n+'!','Hello '+n+'!'))}catch(_e){}},1400);
    }
  }

  function seenMap(){try{return JSON.parse(localStorage.getItem(NOTICE_SEEN_KEY)||'{}')}catch(e){return {}}}
  function saveSeen(m){try{var keys=Object.keys(m);if(keys.length>500){keys.sort(function(a,b){return (+m[b]||0)-(+m[a]||0)});var n={};keys.slice(0,350).forEach(function(k){n[k]=m[k]});m=n;}localStorage.setItem(NOTICE_SEEN_KEY,JSON.stringify(m));}catch(e){}}
  function personName(x){
    x=x||{};var id=String(x.from_id||x.sender_id||x.actor_id||'');var n=String(x.from_name||x.nickname||x.actor_name||'').trim();
    if(!n&&id){try{var p=S().people&&S().people.get&&S().people.get(id);n=String(p&&(p.nickname||p.display_name)||'').trim();}catch(e){}}
    return n||tr('Μέλος','Member');
  }
  function noticeKey(x,source){return String(source||'n')+':'+String(x.id||x.event_id||x.message_id||[x.type,x.from_id,x.created_at].join(':'));}
  function describeNotice(x){
    var type=String(x.type||x.kind||'').toLowerCase(),name=personName(x);
    if(type==='message'||type==='dm'||type==='chat')return {type:'message',text:tr('Νέο μήνυμα από '+name+'.','New message from '+name+'.'),action:function(){try{if(x.from_id&&I().startDM)I().startDM(String(x.from_id));else if(I().page)I().page('dm');}catch(e){}}};
    if(type==='contact'||type==='contact_invite'||type==='friend_request')return {type:'friend',text:tr('Αίτημα φιλίας από '+name+'.','Friend request from '+name+'.'),action:function(){try{I().notifyCenter&&I().notifyCenter();}catch(e){}}};
    if(type==='like'||type==='reaction')return {type:'like',text:tr(name+' έκανε like στη δημοσίευσή σου.',''+name+' liked your post.'),action:function(){try{I().notifyCenter&&I().notifyCenter();}catch(e){}}};
    if(type==='follow'||type==='follower'||type==='new_follower')return {type:'follow',text:tr(name+' σε ακολουθεί.',''+name+' is following you.'),action:function(){try{I().notifyCenter&&I().notifyCenter();}catch(e){}}};
    return null;
  }
  function announce(x,key,seen){
    var d=describeNotice(x);if(!d)return;seen[key]=Date.now();saveSeen(seen);showBil(d.text,d.action);
    var now=Date.now();if(now-lastAlertAt>1200){lastAlertAt=now;try{if(I().playAppAlert)I().playAppAlert('message');}catch(e){}}
  }
  async function monitorNotices(){if(window.__ITHAKI_R10F40_NOTIFICATION_EXCLUSIVE__)return;
    clearTimeout(monitorTimer);var s=S();if(!s||!s.device){monitorTimer=setTimeout(monitorNotices,5000);return;}
    var seen=seenMap(),queue=[];
    try{
      var local=JSON.parse(localStorage.getItem('ith_notifications')||'[]');(local||[]).forEach(function(x){var k=noticeKey(x,'local');if(!seen[k]&&describeNotice(x))queue.push({x:x,k:k,t:+(x.created_at||0)||0});});
    }catch(e){}
    try{
      var f=await fetch(apiBase()+'/api/notifications/light/v249242?room_id='+encodeURIComponent(s.room||'ithaki-phone-test')+'&device_id='+encodeURIComponent(s.device)+'&limit=80',{cache:'no-store'});if(f.ok){var fj=await f.json();(fj.items||[]).filter(function(x){return String(x.relation_to_device||'')==='incoming'||String(x.to_id||'')===String(s.device)}).forEach(function(x){x.type='friend_request';var k=noticeKey(x,'friend');if(!seen[k])queue.push({x:x,k:k,t:+(x.created_at||x.updated_at||0)||0});});}
    }catch(e){}
    try{
      var q=await fetch(apiBase()+'/api/notifications/social/v249247?room_id='+encodeURIComponent(s.room||'ithaki-phone-test')+'&device_id='+encodeURIComponent(s.device)+'&limit=100',{cache:'no-store'});if(q.ok){var qj=await q.json();(qj.items||[]).forEach(function(x){var k=noticeKey(x,'social');if(!seen[k]&&describeNotice(x))queue.push({x:x,k:k,t:+(x.created_at||x.updated_at||0)||0});});}
    }catch(e){}
    queue.sort(function(a,b){return b.t-a.t});queue.slice(0,4).forEach(function(item,i){setTimeout(function(){announce(item.x,item.k,seen)},i*1100);});
    monitorTimer=setTimeout(monitorNotices,15000);
  }

  function install(){
    addCss();forceCanonicalState();fixAllMedia(document);greet();
    if(document.body&&!mediaObserver){mediaObserver=new MutationObserver(function(rs){rs.forEach(function(r){Array.prototype.forEach.call(r.addedNodes||[],fixAllMedia);});});mediaObserver.observe(document.body,{subtree:true,childList:true,attributes:true,attributeFilter:['src','href']});}
    window.addEventListener('ithaki:page-changed',function(){setTimeout(function(){forceCanonicalState();fixAllMedia(document);},40);});
    document.addEventListener('visibilitychange',function(){if(!document.hidden){forceCanonicalState();fixAllMedia(document);monitorNotices();}},{passive:true});
    [100,400,1000,2200,5000].forEach(function(ms){setTimeout(function(){forceCanonicalState();fixAllMedia(document);},ms);});
    setTimeout(monitorNotices,4500);
    Object.assign(I(),{fixMobileMediaV249470:fixAllMedia,showBilNoticeV249470:showBil,showNicknameOnboardingV249470:showOnboarding,v249470ApiBase:apiBase});
    document.documentElement.setAttribute('data-ithaki-v249470','mobile-video-bil-onboarding-avatar-notices');
  }
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',install,{once:true});else install();
})();
