/* OK ITHAKI V249509 - ACTUAL FILE SHARE / DIRECT DM NOTIFICATION / SINGLE BIL */
(function(){'use strict';
if(window.__ITHAKI_V249509_FILE_SHARE_DM_BIL__)return;
window.__ITHAKI_V249509_FILE_SHARE_DM_BIL__={version:'V249509',installedAt:Date.now()};
const $=id=>document.getElementById(id), I=()=>window.ITH||{}, sleep=ms=>new Promise(r=>setTimeout(r,ms));
const en=()=>{try{return (localStorage.getItem('ith_ui_language')||localStorage.getItem('ith_ui_lang')||'el')==='en'}catch(e){return false}};
const toast=(m,ms=4200)=>{try{const t=$('toast');if(t){t.textContent=m;t.classList.add('show');clearTimeout(toast._t);toast._t=setTimeout(()=>t.classList.remove('show'),ms);return}}catch(e){} console.log(m)};
const apiBase=()=>{try{const b=window.AndroidBridge||window.OKITHAKI_ANDROID;if(b&&typeof b.getServerBase==='function'){const x=String(b.getServerBase()||'').trim();if(x)return x.replace(/\/$/,'')}}catch(e){}return 'https://ok-ithaki.gr'};
const room=()=>{try{return localStorage.getItem('ith_room')||'ithaki-phone-test'}catch(e){return'ithaki-phone-test'}};
const device=()=>{try{return localStorage.getItem('ith_device')||''}catch(e){return''}};
const token=()=>{try{return localStorage.getItem('ith_public_token')||localStorage.getItem('ith_token')||''}catch(e){return''}};
function parsePostText(raw){let body=String(raw||''),media=null;try{const o=JSON.parse(body);if(o&&typeof o==='object'){body=String(o.body||o.text||'');media=o.media||null}}catch(e){}return{body,media}}
function mediaUrl(m){return String(m&&(m.url||m.file_url||m.media_url)||'')}
function fullUrl(u){u=String(u||'');if(!u)return'';if(/^https?:/i.test(u)||/^data:/i.test(u))return u;return apiBase()+('/'+u.replace(/^\/+/,''))}
function fileName(url,fallback){try{return decodeURIComponent(String(url).split('/').pop().split('?')[0])||fallback}catch(e){return fallback}}
function blobToData(blob){return new Promise((res,rej)=>{const r=new FileReader();r.onload=()=>res(String(r.result||''));r.onerror=()=>rej(r.error||new Error('read failed'));r.readAsDataURL(blob)})}
async function shareBlob(blob,name,mime){if(window.__ITHAKI_V249523_SHARE_READY__&&I().shareBlobV249523)return I().shareBlobV249523(blob,name,mime);mime=mime||blob.type||'application/octet-stream';name=name||'OK_ITHAKI_file';const b=window.AndroidBridge||window.OKITHAKI_ANDROID;try{if(b&&typeof b.shareBase64File==='function'){const data=await blobToData(blob);const r=String(b.shareBase64File(name,mime,data)||'');if(/^ok/i.test(r))return true;throw new Error(r||'native share failed')}}catch(e){if(String(e&&e.message||e).includes('TransactionTooLarge')){}else console.warn(e)}
try{const f=new File([blob],name,{type:mime});if(navigator.canShare&&navigator.canShare({files:[f]})&&navigator.share){await navigator.share({files:[f],title:'OK ITHAKI'});return true}}catch(e){console.warn(e)}
const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=name;document.body.appendChild(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove()},1200);return true}
async function fetchPost(id){const u=apiBase()+'/api/flow?room_id='+encodeURIComponent(room())+'&visibility=public&limit=300&lite=1&viewer_id='+encodeURIComponent(device());const h={};const t=token();if(t)h['X-ITHAKI-TOKEN']=t;const r=await fetch(u,{cache:'no-store',headers:h});if(!r.ok)throw new Error('feed '+r.status);const d=await r.json();return (d.posts||[]).find(p=>String(p.post_id||'')===String(id))||null}
async function sharePostFile(id){try{const p=await fetchPost(id);if(!p)throw new Error(en()?'Post not found':'Η δημοσίευση δεν βρέθηκε');const x=parsePostText(p.text),m=x.media||{};const url=fullUrl(mediaUrl(m));if(url){const name=fileName(url,m.filename||m.name||('ITHAKI_'+id));if(I().shareMediaFile)return await I().shareMediaFile(url,name,m.mime_type||m.type||'',m.kind||'file')}
const lines=[x.body||'',m.question||'',...(Array.isArray(m.options)?m.options:[])].filter(Boolean);const text=(lines.join('\n')||String(p.text||'')).trim();await shareBlob(new Blob([text],{type:'text/plain;charset=utf-8'}),'ITHAKI_'+String(id).replace(/[^a-z0-9_-]/gi,'_')+'.txt','text/plain');toast(en()?'The actual post file was shared.':'Κοινοποιήθηκε το πραγματικό αρχείο της δημοσίευσης.');return false}catch(e){toast((en()?'Share failed: ':'Η κοινοποίηση απέτυχε: ')+(e.message||e),6500);return false}}
function installShare(){const o=I();if(!o||!o.sharePost)return false;if(!o.sharePost.__v249509){const old=o.sharePost;o.sharePost=function(id){return sharePostFile(id)};o.sharePost.__v249509=true;o.sharePost.__old=old}
if(o.share&&!o.share.__v249509){const oldShare=o.share;o.share=function(url,text){const u=String(url||'');if(/\/api\/media\/file\/|\.(mp4|mov|webm|3gp|jpe?g|png|gif|webp|pdf|docx?|xlsx?|pptx?|zip|mp3|m4a|wav)(?:[?#]|$)/i.test(u)&&o.shareMediaFile)return o.shareMediaFile(fullUrl(u),fileName(u,'OK_ITHAKI_file'),'','file');return oldShare(url,text)};o.share.__v249509=true}
return true}
function messageLaunch(){try{const u=new URL(location.href),kind=String(u.searchParams.get('kind')||u.searchParams.get('fcm_kind')||''),dm=u.searchParams.get('dm')||u.searchParams.get('peer')||u.searchParams.get('peer_id')||u.searchParams.get('from_id')||'';if(!dm||!(kind==='message'||u.searchParams.get('message_id')||u.searchParams.get('direct_open_dm')==='1'))return false;const o=I();if(o.page)o.page('dm');Promise.resolve(o.loadPeople?o.loadPeople():null).finally(()=>Promise.resolve(o.startDM?o.startDM(dm):null).finally(()=>setTimeout(()=>{try{o.showDMChatScreenV249235&&o.showDMChatScreenV249235()}catch(e){}},80)));return true}catch(e){return false}}
function bilFace(){return '<span class="ith509BilFace"><i class="shell"></i><i class="head"><i class="eye l"></i><i class="eye r"></i><i class="mouth"></i></i></span>'}
function addBilCss(){if($('ith509BilCss'))return;const s=document.createElement('style');s.id='ith509BilCss';s.textContent='.ith509BilFace{position:relative;width:54px;height:48px;display:block}.ith509BilFace .shell{position:absolute;left:8px;top:19px;width:36px;height:25px;border-radius:55% 55% 42% 42%;background:radial-gradient(circle at 45% 25%,#ffe198 0 18%,#61bd87 19% 55%,#246b50 56% 100%)}.ith509BilFace .head{position:absolute;left:19px;top:2px;width:23px;height:23px;border-radius:50%;background:#7bd99e}.ith509BilFace .eye{position:absolute;top:7px;width:4px;height:6px;border-radius:50%;background:#10231e}.ith509BilFace .eye.l{left:5px}.ith509BilFace .eye.r{right:5px}.ith509BilFace .mouth{position:absolute;left:7px;top:15px;width:9px;height:4px;border-bottom:2px solid #17392e;border-radius:0 0 9px 9px}';document.head.appendChild(s)}
function notificationHosts(){return ['notifySettingsV249258','notificationSettingsV249238','ithNotificationSettingsV249238','notificationCenter'].map($).filter(Boolean)}
function ensureSingleBil(){if(window.__ITHAKI_V249525_NOTIFICATION_OWNER__||window.__ITHAKI_V249523_SHARE_BIL_OWNER__)return false;addBilCss();const hosts=notificationHosts();if(!hosts.length)return false;document.querySelectorAll('#ith477BilNotificationCard,#ith509BilNotificationCard,[data-bil-notification-card]').forEach(x=>x.remove());hosts.forEach((h,i)=>{h.querySelectorAll('*').forEach(x=>{if(x.children.length<8&&/^Bil$/i.test(String(x.textContent||'').trim())){const c=x.closest('.card,section');if(c)c.remove()}});if(i>0)return;const on=(()=>{try{return localStorage.getItem('ith_bil_enabled_v249461')!=='0'}catch(e){return true}})();const d=document.createElement('section');d.id='ith509BilNotificationCard';d.className='card';d.dataset.bilNotificationCard='1';d.innerHTML='<div style="display:flex;align-items:center;gap:10px">'+bilFace()+'<div><b>Bil</b><div class="date">'+(en()?'One Bil, with two eyes, only in Notifications.':'Ένας Bil, με δύο μάτια, μόνο στις Ειδοποιήσεις.')+'</div></div></div><div class="row" style="margin-top:9px"><button class="btn '+(on?'green':'')+'" data-bil509="1">'+(en()?'Enabled':'Ενεργός')+'</button><button class="btn '+(!on?'green':'')+'" data-bil509="0">'+(en()?'Disabled':'Ανενεργός')+'</button></div>';d.onclick=e=>{const b=e.target.closest('[data-bil509]');if(!b)return;try{localStorage.setItem('ith_bil_enabled_v249461',b.dataset.bil509==='1'?'1':'0');localStorage.setItem('ithaki_companion_v249258',b.dataset.bil509==='1'?'bil':'none')}catch(_){}ensureSingleBil()};h.prepend(d)});return true}
function wrapNotifications(){const o=I();['notifyCenter','openNotificationSettingsV249238'].forEach(k=>{const f=o[k];if(typeof f==='function'&&!f.__v249509){o[k]=function(){const r=f.apply(this,arguments);setTimeout(ensureSingleBil,30);setTimeout(ensureSingleBil,300);return r};o[k].__v249509=true}})}
function install(){if(!installShare())return setTimeout(install,120);wrapNotifications();ensureSingleBil();messageLaunch();setTimeout(messageLaunch,700);new MutationObserver(()=>{clearTimeout(install._m);install._m=setTimeout(()=>{ensureSingleBil();installShare()},80)}).observe(document.body,{subtree:true,childList:true});document.documentElement.setAttribute('data-ithaki-v249509','actual-file-share-direct-dm-single-bil')}
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',install,{once:true});else install();
})();
