/* OK ITHAKI V249473
 * Definitive single-audio Feed controller and robust Bil on/off rendering.
 * Only the most visible Feed video may play with sound. The notification Bil
 * uses an independent full body with exactly two eyes and one mouth.
 */
(function(){
  'use strict';
  if(window.__ITHAKI_V249475_OWNS_BIL__||window.__ITHAKI_V249475_OWNS_AUDIO__) return;
  if(window.__ITHAKI_V249473_COMPLETE__) return;
  window.__ITHAKI_V249473_COMPLETE__={version:'V249473',installedAt:Date.now()};
  window.__ITHAKI_V249473_FEED_AUDIO_OWNER__=true;

  var BIL_KEY='ith_bil_enabled_v249461';
  var BIL_ID='ithBilGreenTurtleV249461';
  var BIL_MENU_ID='ithBilMenuV249461';
  var SOUND_KEY='ith_video_sound_enabled_v249220';
  var active=null, unlocked=false, observer=null, mutation=null, scheduled=false;
  var known=[];

  function I(){return window.ITH||(window.ITH={});}
  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 esc(v){return String(v==null?'':v).replace(/[&<>\"]/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]})}
  function bilEnabled(){try{return localStorage.getItem(BIL_KEY)!=='0'}catch(e){return true}}
  function onFeed(){return !!(document.body&&document.body.dataset.page==='feed')}

  function addCss(){
    if(document.getElementById('ithV249473Css'))return;
    var s=document.createElement('style');s.id='ithV249473Css';s.textContent=`
      .bil473{position:relative;display:block;width:64px;height:54px;overflow:visible;filter:drop-shadow(0 6px 9px rgba(0,0,0,.28))}
      .bil473 .bil473Shell{position:absolute;left:7px;top:17px;width:48px;height:31px;border-radius:52% 48% 46% 54%;background:linear-gradient(145deg,#66c96e,#176936);border:2px solid rgba(215,255,219,.72);box-shadow:inset -7px -7px 0 rgba(0,55,24,.20)}
      .bil473 .bil473Shell:before,.bil473 .bil473Shell:after{content:"";position:absolute;background:rgba(230,255,226,.24)}
      .bil473 .bil473Shell:before{left:21px;top:2px;width:2px;height:25px;transform:rotate(8deg)}
      .bil473 .bil473Shell:after{left:7px;top:13px;width:34px;height:2px;transform:rotate(-5deg)}
      .bil473 .bil473Head{position:absolute;right:0;top:6px;width:27px;height:26px;border-radius:48% 52% 50% 46%;background:linear-gradient(145deg,#86df83,#2c8d48);border:2px solid rgba(224,255,225,.78)}
      .bil473 .bil473Eye{position:absolute;top:7px;width:5px;height:6px;border-radius:50%;background:#06140a;box-shadow:0 0 0 1px rgba(255,255,255,.46)}
      .bil473 .bil473Eye.left{left:6px}.bil473 .bil473Eye.right{right:6px}
      .bil473 .bil473Mouth{position:absolute;left:8px;top:16px;width:10px;height:5px;border-bottom:2px solid #08210e;border-radius:0 0 10px 10px}
      .bil473 .bil473Foot{position:absolute;top:41px;width:13px;height:8px;border-radius:50%;background:#3b9e50;border:1px solid rgba(220,255,220,.55)}
      .bil473 .bil473Foot.left{left:10px}.bil473 .bil473Foot.right{left:37px}
      .bil473 .bil473Tail{position:absolute;left:1px;top:29px;width:13px;height:9px;background:#3e9e51;clip-path:polygon(100% 0,0 50%,100% 100%)}
      #${BIL_ID} .bil473{margin:auto}
      #${BIL_ID}[data-bil473-enabled="0"]{display:none!important;visibility:hidden!important;pointer-events:none!important}
      .bil473Toggle{display:grid!important;grid-template-columns:1fr 1fr!important;gap:8px!important;margin-top:10px!important}
      .bil473Toggle button{min-height:48px!important;border-radius:12px!important;font-weight:800!important}
      .bil473Toggle button.active{outline:2px solid rgba(100,230,135,.95)!important;background:rgba(30,125,66,.38)!important}
      .bil473Preview{display:flex!important;align-items:center!important;gap:13px!important;padding:12px!important;border-radius:14px!important;background:rgba(10,35,26,.44)!important;margin-top:10px!important}
      #feedPage video[data-ith-active-audio-v249473="1"]{outline:1px solid rgba(255,255,255,.07)!important}
    `;document.head.appendChild(s);
  }

  function bilFace(){return '<span class="bil473" aria-hidden="true"><i class="bil473Tail"></i><i class="bil473Foot left"></i><i class="bil473Foot right"></i><i class="bil473Shell"></i><i class="bil473Head"><i class="bil473Eye left"></i><i class="bil473Eye right"></i><i class="bil473Mouth"></i></i></span>'}

  function ensureBil(){if(window.__ITHAKI_V249523_SHARE_BIL_OWNER__)return null;
    addCss();
    var enabled=bilEnabled(),b=document.getElementById(BIL_ID);
    if(!b&&enabled&&document.body){
      b=document.createElement('button');b.id=BIL_ID;b.type='button';
      b.onclick=function(ev){ev.preventDefault();ev.stopPropagation();var fn=I().openBilV249461;if(typeof fn==='function')return fn()};
      document.body.appendChild(b);
    }
    if(b){
      if(!b.querySelector('.bil473'))b.innerHTML=bilFace();
      b.setAttribute('data-bil473-enabled',enabled?'1':'0');
      b.setAttribute('aria-label',tr('Άνοιγμα Bil','Open Bil'));
      b.style.display=enabled&&document.body&&document.body.dataset.page==='home'?'grid':'none';
    }
    var menu=document.getElementById(BIL_MENU_ID);
    if(menu){var slot=menu.querySelector('[data-bil473-face]');if(slot)slot.innerHTML=bilFace()}
  }

  function setBil(on){
    try{localStorage.setItem(BIL_KEY,on?'1':'0');localStorage.setItem('ithaki_companion_v249258',on?'sokratakis':'none')}catch(e){}
    try{if(typeof window.setIthakiCompanionV249258==='function')window.setIthakiCompanionV249258(on?'sokratakis':'none')}catch(e){}
    if(document.body)document.body.classList.toggle('ithBilDisabledV249471',!on);
    ensureBil();renderNotificationSettings();
    try{var toast=I().toast||window.toast;if(typeof toast==='function')toast(on?tr('Ο Bil ενεργοποιήθηκε.','Bil was enabled.'):tr('Ο Bil απενεργοποιήθηκε.','Bil was disabled.'))}catch(e){}
    return false;
  }

  function currentNotifyMode(){try{return localStorage.getItem('ithaki_push_mode_v249258')||'fcm_default'}catch(e){return 'fcm_default'}}
  function renderNotificationSettings(){
    var el=document.getElementById('notifySettingsV249258');if(!el)return '';
    var m=currentNotifyMode(),on=bilEnabled();
    var modes=english()?[
      ['fcm_default','1. FCM default','Closed app through Firebase/FCM and open app through the internal bell. Recommended.'],
      ['background','2. Background','Gentler operation while the app is in the background.'],
      ['open_app','3. Open app','Notifications only while you are inside ITHAKI.'],
      ['stay_awake','4. Always awake','Keeps a live connection. Faster, but may use more battery.'],
      ['no_closed','5. No closed-app notifications','No FCM push while the application is closed.']
    ]:[
      ['fcm_default','1. FCM προεπιλογή','Κλειστή εφαρμογή με Firebase/FCM και ανοιχτή εφαρμογή με το εσωτερικό καμπανάκι. Προτείνεται.'],
      ['background','2. Παρασκήνιο','Πιο ήπια λειτουργία όταν η εφαρμογή είναι στο παρασκήνιο.'],
      ['open_app','3. Ανοιχτή εφαρμογή','Ειδοποιήσεις μόνο όσο βρίσκεσαι μέσα στην ΙΘΑΚΗ.'],
      ['stay_awake','4. Δεν κοιμάται','Κρατά ζωντανή σύνδεση. Πιο άμεσο, αλλά μπορεί να χρησιμοποιεί περισσότερη μπαταρία.'],
      ['no_closed','5. Χωρίς ειδοποιήσεις με κλειστή εφαρμογή','Δεν εμφανίζεται FCM push όταν η εφαρμογή είναι κλειστή.']
    ];
    var cards=modes.map(function(x){return '<button class="modeCardV249258 '+(m===x[0]?'active':'')+'" onclick="return ITH.setNotificationMode(\''+x[0]+'\')"><b>'+esc(x[1])+'</b><small>'+esc(x[2])+'</small></button>'}).join('');
    el.innerHTML='<div class="card"><b>🔔 '+esc(tr('Επιλογές ειδοποιήσεων','Notification options'))+'</b><div class="date">'+esc(tr('Διάλεξε έναν τρόπο ειδοποίησης, ώστε να μην δημιουργούνται διπλά μηνύματα ή κλήσεις.','Choose one notification mode so duplicate messages or calls are not created.'))+'</div><div class="modeGridV249258" style="margin-top:10px">'+cards+'</div></div>'+
      '<div class="card"><b>🐢 Bil</b><div class="date">'+esc(tr('Ο Bil είναι τοπικός στη συσκευή και δεν στέλνει δεδομένα στον server.','Bil stays locally on the device and sends no data to the server.'))+'</div><div class="bil473Preview">'+bilFace()+'<div><b>Bil</b><div>'+esc(on?tr('Εμφανίζεται στην Αρχική.','Shown on Home.'):tr('Δεν εμφανίζεται στην Αρχική.','Hidden from Home.'))+'</div><small>'+esc(tr('Δύο μάτια και ένα στόμα.','Two eyes and one mouth.'))+'</small></div></div><div class="bil473Toggle"><button class="'+(on?'active':'')+'" onclick="return ITH.setBilNotificationCompanionV249473(true)">'+esc(tr('Ενεργοποιημένος','Enabled'))+'</button><button class="'+(!on?'active':'')+'" onclick="return ITH.setBilNotificationCompanionV249473(false)">'+esc(tr('Απενεργοποιημένος','Disabled'))+'</button></div></div>';
    return el.innerHTML;
  }

  function installBilOverrides(){
    I().setBilNotificationCompanionV249473=setBil;
    window.setBilNotificationCompanionV249473=setBil;
    I().renderNotificationModeSettingsV249258=renderNotificationSettings;
    window.renderNotificationModeSettingsV249258=renderNotificationSettings;
    I().renderNotificationSettingsV249473=renderNotificationSettings;
  }

  function allMedia(){
    var arr=[];try{arr=Array.prototype.slice.call(document.querySelectorAll('#feedPage video,#feedPage audio,video.feedVideo'))}catch(e){}
    arr.forEach(function(m){if(known.indexOf(m)<0)known.push(m)});
    known=known.filter(function(m){return m&&typeof m.pause==='function'});
    return known.slice();
  }
  function ratio(m){
    try{
      var r=m.getBoundingClientRect(),vw=innerWidth||document.documentElement.clientWidth,vh=innerHeight||document.documentElement.clientHeight;
      if(r.width<=0||r.height<=0)return 0;
      var w=Math.max(0,Math.min(vw,r.right)-Math.max(0,r.left));
      var h=Math.max(0,Math.min(vh,r.bottom)-Math.max(0,r.top));
      return Math.max(0,Math.min(1,(w*h)/(r.width*r.height)));
    }catch(e){return 0}
  }
  function stop(m){
    if(!m)return;try{m.pause()}catch(e){}
    try{m.muted=true;m.defaultMuted=true;m.volume=0;m.removeAttribute('data-ith-active-audio-v249473')}catch(e){}
  }
  function winner(candidate){
    var best=null,bestRatio=0;
    allMedia().forEach(function(m){if(!m.isConnected||!m.closest||!m.closest('#feedPage'))return;var r=ratio(m);if(r>bestRatio){best=m;bestRatio=r}});
    if(candidate&&candidate.isConnected&&candidate.closest&&candidate.closest('#feedPage')){var cr=ratio(candidate);if(cr>=bestRatio-.03&&cr>=.30){best=candidate;bestRatio=cr}}
    return bestRatio>=.22?best:null;
  }
  function enforce(play,candidate){
    if(!onFeed()||document.hidden){active=null;allMedia().forEach(stop);return null}
    var next=winner(candidate),changed=next!==active;active=next;
    allMedia().forEach(function(m){
      if(m!==active){stop(m);return}
      try{m.defaultMuted=false;m.muted=!unlocked;m.volume=unlocked?1:0;m.removeAttribute('muted');m.setAttribute('playsinline','');m.setAttribute('webkit-playsinline','');m.setAttribute('data-ith-active-audio-v249473','1')}catch(e){}
    });
    if(active&&unlocked&&(play||changed)){try{var p=active.play();if(p&&p.catch)p.catch(function(){})}catch(e){}}
    return active;
  }
  function stopAll(){active=null;allMedia().forEach(stop)}
  function schedule(play,candidate){
    if(scheduled)return;scheduled=true;
    requestAnimationFrame(function(){scheduled=false;enforce(!!play,candidate||null)});
  }
  function watchMedia(){
    var els=[];try{els=Array.prototype.slice.call(document.querySelectorAll('#feedPage video,#feedPage audio,video.feedVideo'))}catch(e){}
    els.forEach(function(m){
      if(known.indexOf(m)<0)known.push(m);
      if(observer&&!m.__ith473Observed){try{observer.observe(m);m.__ith473Observed=true}catch(e){}}
    });
  }
  function installAudio(){
    try{localStorage.setItem(SOUND_KEY,'1')}catch(e){}
    I().enforceSingleFeedAudioV249473=enforce;I().stopAllFeedMediaV249473=stopAll;
    try{observer=new IntersectionObserver(function(){schedule(false)}, {root:null,threshold:[0,.1,.22,.35,.5,.65,.8,.95,1]})}catch(e){observer=null}
    watchMedia();
    document.addEventListener('play',function(ev){var m=ev.target;if(!m||!m.closest||!m.closest('#feedPage'))return;var w=winner(m);if(w!==m){stop(m);schedule(false);return}active=m;enforce(false,m)},true);
    document.addEventListener('volumechange',function(ev){var m=ev.target;if(!m||!m.closest||!m.closest('#feedPage'))return;if(m!==winner(m)&&!m.muted)stop(m)},true);
    ['pointerdown','touchstart','click'].forEach(function(n){document.addEventListener(n,function(ev){if(ev.target&&ev.target.closest&&ev.target.closest('#feedPage')){unlocked=true;enforce(true)}},{capture:true,passive:true})});
    window.addEventListener('scroll',function(){enforce(false);schedule(false)},{capture:true,passive:true});
    window.addEventListener('scrollend',function(){enforce(true)},{capture:true,passive:true});
    window.addEventListener('resize',function(){schedule(false)},{passive:true});
    window.addEventListener('pagehide',stopAll);
    window.addEventListener('blur',function(){if(document.hidden)stopAll()});
    document.addEventListener('visibilitychange',function(){if(document.hidden)stopAll();else schedule(false)},{passive:true});
    window.addEventListener('ithaki:page-changed',function(ev){var p=String(ev&&ev.detail&&ev.detail.page||document.body&&document.body.dataset.page||'');if(p!=='feed')stopAll();else setTimeout(function(){watchMedia();enforce(unlocked)},40)});
    if(document.body){mutation=new MutationObserver(function(){watchMedia();schedule(false)});mutation.observe(document.body,{subtree:true,childList:true})}
    setInterval(function(){if(onFeed()){watchMedia();enforce(false)}else if(active)stopAll()},120);
  }

  function run(){addCss();installBilOverrides();ensureBil();if(document.getElementById('notifySettingsV249258'))renderNotificationSettings();watchMedia();if(onFeed())enforce(false);document.documentElement.setAttribute('data-ithaki-v249473','feed-audio-bil-toggle-reset-tool')}
  function install(){installAudio();run();window.addEventListener('ithaki:page-changed',function(){setTimeout(run,20)});window.addEventListener('storage',run);setInterval(run,650)}
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',install,{once:true});else install();
})();
