/* OK ITHAKI V249390 — strict friend identity, invitations and acceptance.
   Device/member IDs are authoritative. Names and avatars are display-only. */
(function(){
  'use strict';
  if(window.__ITHAKI_FRIEND_IDENTITY_V249390__)return;
  window.__ITHAKI_FRIEND_IDENTITY_V249390__=1;

  const VERSION='V249391-friend-identity-acceptance-unified-flow';
  const $=id=>document.getElementById(id);
  const esc=s=>String(s==null?'':s).replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));
  const js=s=>String(s==null?'':s).replace(/\\/g,'\\\\').replace(/'/g,"\\'").replace(/\r/g,'').replace(/\n/g,'\\n');
  const stateObj=()=>{try{return window.state||state||{}}catch(e){return{}}};
  const room=()=>String(stateObj().room||localStorage.getItem('ith_room')||'ithaki-phone-test');
  const device=()=>String(localStorage.getItem('ith_device')||stateObj().device||'').trim();
  const apiBase=()=>String(stateObj().api||location.origin||'').replace(/\/$/,'');
  const notice=(m,t=4800)=>{try{if(typeof window.toast==='function')window.toast(m,t);else console.log(m)}catch(e){console.log(m)}};
  const currentName=()=>String(stateObj().name||localStorage.getItem('ith_name')||'Μέλος');

  function candidateIds(){
    const out=[];
    const add=v=>{v=String(v||'').trim();if(v&&!out.includes(v))out.push(v)};
    add(device());
    try{const fn=window.ITH&&ITH.accountDeviceCandidatesV249386;if(typeof fn==='function')(fn()||[]).forEach(add)}catch(e){}
    try{add(stateObj().device);add(localStorage.getItem('device_id'))}catch(e){}
    return out.slice(0,4);
  }
  async function request(path,opt={}){
    const headers=Object.assign({'Content-Type':'application/json'},opt.headers||{});
    const r=await fetch(apiBase()+path,Object.assign({cache:'no-store',credentials:'same-origin',headers},opt));
    let d=null;try{d=await r.json()}catch(e){}
    if(!r.ok||!d||d.ok===false){
      const msg=(d&&((typeof d.detail==='string'&&d.detail)||(d.detail&&d.detail.message)||d.message||d.reason))||('HTTP '+r.status);
      throw new Error(String(msg));
    }
    return d;
  }
  function canonicalPerson(item){
    const peer=item&&item.peer||{};
    const id=String(item&&item.peer_id||peer.device_id||peer.id||'').trim();
    const name=String(item&&item.peer_name||peer.nickname||peer.name||'Μέλος');
    const avatar=String(item&&item.peer_avatar||peer.avatar||peer.photo||'');
    const p={id,device_id:id,nickname:name,avatar,last_seen:Number(peer.last_seen||0),online:!!peer.online};
    try{
      const s=stateObj();
      if(s.people&&typeof s.people.set==='function'){
        const old=s.people.get(id)||{};
        s.people.set(id,Object.assign({},old,p,{nickname:name||old.nickname||'Μέλος',avatar:avatar||old.avatar||''}));
      }
    }catch(e){}
    return p;
  }
  function avatar(p){
    try{if(typeof window.avatarHtml==='function')return window.avatarHtml(p)}catch(e){}
    const a=String(p&&p.avatar||'');
    if(a&&(/^(data:image|https?:|\/api\/)/.test(a)))return `<span class="avatar"><img src="${esc(a)}"></span>`;
    return `<span class="avatar">${esc(String(p&&p.nickname||'Μ')[0]||'Μ')}</span>`;
  }
  function fmtTime(v){
    try{if(typeof window.fmt==='function')return window.fmt(v);const n=Number(v||0);return new Date(n>1e12?n:n*1000).toLocaleString('el-GR')}catch(e){return''}
  }
  function pendingActionExists(){
    try{return !!localStorage.getItem('ith_pending_global_friend_action_v249386')}catch(e){return false}
  }
  async function loadFriendItems(){
    const aliases=candidateIds().filter(x=>x!==device()).join(',');
    return request('/api/social/friend/notifications_v249390?room_id='+encodeURIComponent(room())+'&device_id='+encodeURIComponent(device())+'&aliases='+encodeURIComponent(aliases)+'&limit=160&_v='+Date.now());
  }
  function friendCard(item){
    const p=canonicalPerson(item);
    const incoming=!!item.can_accept;
    const repair=!!item.old_device_repair;
    return `<article class="ithFriendCard390" data-friend-event390="${esc(item.id||'')}">
      ${avatar(p)}
      <div class="ithFriendText390"><b>${incoming?'🤝 Αίτημα φιλίας':'⏳ Αίτημα σε αναμονή'}</b><strong>${esc(p.nickname)}</strong><small>${esc(fmtTime(item.created_at||item.updated_at))}${repair?' · παλιό αναγνωριστικό συσκευής':''}</small><p>${incoming?'Το συγκεκριμένο μέλος σού έστειλε αίτημα.':'Περιμένει αποδοχή από το συγκεκριμένο μέλος.'}</p></div>
      <div class="ithFriendActions390">${incoming?`<button class="btn green" onclick="return ITH.respondFriendV249390('${js(item.id)}',true,'${js(p.id)}')">Αποδοχή</button><button class="btn" onclick="return ITH.respondFriendV249390('${js(item.id)}',false,'${js(p.id)}')">Απόρριψη</button>`:`<button class="btn" onclick="return ITH.member&&ITH.member('${js(p.id)}')">Προφίλ</button>`}</div>
    </article>`;
  }
  function ensureCss(){
    if($('ithFriendIdentityCss390'))return;
    const st=document.createElement('style');st.id='ithFriendIdentityCss390';st.textContent=`
      .ithFriendCenter390{display:grid;gap:10px;padding:12px 12px 90px}.ithFriendHead390{position:sticky;top:0;z-index:5;display:flex;align-items:center;gap:8px;padding:10px;border-radius:18px;background:rgba(5,10,18,.94);border:1px solid rgba(255,215,110,.20);backdrop-filter:blur(14px)}.ithFriendHead390 b{flex:1;color:#ffe094}.ithFriendCard390{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:11px;align-items:center;padding:12px;border-radius:19px;background:rgba(255,255,255,.065);border:1px solid rgba(255,255,255,.11)}.ithFriendCard390 .avatar{width:48px!important;height:48px!important;border-radius:50%!important;display:grid!important;place-items:center!important;overflow:hidden!important;background:rgba(255,255,255,.1)}.ithFriendCard390 .avatar img{width:100%;height:100%;object-fit:cover;border-radius:50%}.ithFriendText390{min-width:0}.ithFriendText390 b,.ithFriendText390 strong,.ithFriendText390 small{display:block}.ithFriendText390 strong{color:#fff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.ithFriendText390 small{color:rgba(255,255,255,.56)}.ithFriendText390 p{margin:5px 0 0;color:rgba(255,255,255,.78)}.ithFriendActions390{display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end}.ithFriendInfo390{padding:12px;border-radius:17px;background:rgba(255,215,110,.08);border:1px solid rgba(255,215,110,.18);color:#f5e4b7}@media(max-width:650px){.ithFriendCard390{grid-template-columns:auto 1fr}.ithFriendActions390{grid-column:1/3}.ithFriendActions390 .btn{flex:1}}
    `;document.head.appendChild(st);
  }
  async function respond(eventId,accepted,peerId){
    eventId=String(eventId||'').trim();peerId=String(peerId||'').trim();
    if(!eventId)return false;
    try{
      const d=await request('/api/social/friend/respond_v249390',{method:'POST',body:JSON.stringify({room_id:room(),id:eventId,device_id:device(),device_aliases:candidateIds(),accepted:accepted===true})});
      if(d.status==='accepted'){
        const friend=canonicalPerson({peer:d.friend||{},peer_id:d.friend_id||peerId,peer_name:d.friend&&d.friend.nickname,peer_avatar:d.friend&&d.friend.avatar});
        try{let ids=JSON.parse(localStorage.getItem('ith_contacts')||'[]');if(!Array.isArray(ids))ids=[];if(friend.id&&!ids.includes(friend.id))ids.push(friend.id);localStorage.setItem('ith_contacts',JSON.stringify(ids))}catch(e){}
        try{window.dispatchEvent(new CustomEvent('ithaki-friend-accepted-v249386',{detail:{peer_id:friend.id,event_id:eventId}}))}catch(e){}
        try{if(window.ITH&&typeof ITH.friendAcceptedRecheckV249386==='function')ITH.friendAcceptedRecheckV249386()}catch(e){}
        try{if(typeof window.refreshFriendsForMessagesV249246==='function')await window.refreshFriendsForMessagesV249246(false);else if(window.ITH&&typeof ITH.refreshFriendsForMessagesV249246==='function')await ITH.refreshFriendsForMessagesV249246(false)}catch(e){}
        notice(d.device_repair?'Η φιλία έγινε αποδεκτή και συνδέθηκε με τη σημερινή συσκευή.':'Η φιλία έγινε αποδεκτή.',5200);
        try{const menu=$('memberMenu');if(menu)menu.classList.remove('show')}catch(e){}
        if(friend.id&&!pendingActionExists())setTimeout(()=>{try{if(window.ITH&&typeof ITH.startDM==='function')ITH.startDM(friend.id)}catch(e){}},220);
      }else{
        notice('Το αίτημα απορρίφθηκε.',4200);await openFriendCenter();
      }
    }catch(e){notice('Δεν ολοκληρώθηκε η απάντηση: '+String(e.message||e),6500)}
    return false;
  }
  async function sendRequest(peerId){
    peerId=String(peerId||'').trim();
    if(!peerId||peerId===device()){notice('Δεν γίνεται αίτημα φιλίας στον εαυτό σου.');return false}
    let p={};try{p=stateObj().people&&stateObj().people.get(peerId)||{}}catch(e){}
    try{
      const d=await request('/api/social/friend/request_v249390',{method:'POST',body:JSON.stringify({room_id:room(),from_id:device(),from_name:currentName(),to_id:peerId,to_name:p.nickname||'Μέλος'})});
      canonicalPerson({peer:d.to_profile||{},peer_id:peerId});
      if(d.already_friends){notice('Είστε ήδη φίλοι.');setTimeout(()=>{try{ITH.startDM(peerId)}catch(e){}},350)}
      else if(d.reverse_pending){notice('Το μέλος έχει ήδη στείλει αίτημα. Άνοιξε το καμπανάκι για αποδοχή.',6000);setTimeout(openFriendCenter,350)}
      else notice(d.duplicate?'Το αίτημα υπάρχει ήδη και περιμένει αποδοχή.':'Το αίτημα φιλίας στάλθηκε στο σωστό μέλος.',5200);
    }catch(e){notice('Δεν στάλθηκε το αίτημα: '+String(e.message||e),6500)}
    return false;
  }
  function strictFriendDecisionV249390(value){
    if(value===true||value===1)return true;
    if(value===false||value===0||value==null)return false;
    const text=String(value).trim().toLowerCase();
    if(['0','false','no','reject','rejected','deny','denied','decline','declined'].includes(text))return false;
    if(['1','true','yes','accept','accepted','approve','approved','ok'].includes(text))return true;
    return false;
  }
  async function legacyRespond(eventId,value,peerId){
    const accepted=strictFriendDecisionV249390(value);
    return respond(eventId,accepted,peerId);
  }
  async function legacyByPeer(peerId,accepted){
    try{
      const d=await loadFriendItems();
      const item=(d.items||[]).find(x=>x.can_accept&&String(x.peer_id||'')===String(peerId||''));
      if(!item){notice('Δεν βρέθηκε ενεργό εισερχόμενο αίτημα από αυτό το μέλος.',5500);return false}
      return respond(item.id,accepted,peerId);
    }catch(e){notice('Δεν φορτώθηκε το αίτημα: '+String(e.message||e),6000);return false}
  }
  function genericOtherNotice(n){
    const type=String(n&&n.type||'').toLowerCase();
    if(type==='contact'||type==='contact_invite'||type==='friend_request')return'';
    const id=String(n&&n.from_id||n&&n.sender_id||'');
    let p={id,device_id:id,nickname:String(n&&n.from_name||n&&n.nickname||'Μέλος'),avatar:''};
    try{const known=stateObj().people&&stateObj().people.get(id);if(known)p=known}catch(e){}
    const label=type==='message'?'Νέο μήνυμα':type==='like'||type==='reaction'?'Νέα αντίδραση':type==='post'||type==='follow_post'?'Νέα δημοσίευση':'Ειδοποίηση';
    return `<article class="ithFriendCard390">${avatar(p)}<div class="ithFriendText390"><b>${esc(label)}</b><strong>${esc(p.nickname||'Μέλος')}</strong><small>${esc(fmtTime(n.created_at||Date.now()))}</small><p>${esc(n.text||n.body||'')}</p></div><div class="ithFriendActions390">${type==='message'&&id?`<button class="btn green" onclick="return ITH.startDM('${js(id)}')">Άνοιγμα</button>`:''}</div></article>`;
  }
  async function openFriendCenter(){
    ensureCss();
    const menu=$('memberMenu');if(!menu)return false;
    menu.classList.add('show','fullAvatarMenuV249231');
    menu.innerHTML=`<div class="ithFriendCenter390"><div class="ithFriendHead390"><button class="icon" onclick="ITH.closeMember&&ITH.closeMember()">‹</button><b>🤝 Αιτήματα και ειδοποιήσεις μελών</b><button class="icon" onclick="ITH.closeMember&&ITH.closeMember()">×</button></div><div id="ithFriendList390"><div class="card">Έλεγχος αιτημάτων…</div></div></div>`;
    try{
      const d=await loadFriendItems();
      let others=[];
      try{if(typeof window.v249247RefreshServerNotifications==='function'){const x=await window.v249247RefreshServerNotifications();others=x.items||[]}}catch(e){}
      try{if(typeof window.localNotices==='function')others=others.concat(window.localNotices().filter(n=>!n.read))}catch(e){}
      const friendHtml=(d.items||[]).map(friendCard).join('');
      const seen=new Set();const otherHtml=others.filter(n=>{const k=String(n.id||n.event_id||n.type||'')+'|'+String(n.created_at||'');if(seen.has(k))return false;seen.add(k);return true}).map(genericOtherNotice).filter(Boolean).join('');
      const box=$('ithFriendList390');if(box)box.innerHTML=`<div class="ithFriendInfo390">Το avatar και το όνομα αντιστοιχίζονται πάντα από το πραγματικό <b>peer_id</b>. Μόνο ο παραλήπτης βλέπει Αποδοχή/Απόρριψη.</div>${friendHtml}${otherHtml||''}${!friendHtml&&!otherHtml?'<div class="card">Δεν υπάρχουν νέες ειδοποιήσεις.</div>':''}`;
    }catch(e){const box=$('ithFriendList390');if(box)box.innerHTML=`<div class="card"><b>Δεν φορτώθηκαν τα αιτήματα.</b><div class="date">${esc(e.message||e)}</div><button class="btn" onclick="ITH.notifyCenter()">Δοκιμή ξανά</button></div>`}
    return false;
  }
  function installOverrides(){
    window.ITH=window.ITH||{};
    window.respondFriendV249390=respond;
    window.strictFriendDecisionV249390=strictFriendDecisionV249390;
    window.sendFriendProposalV249390=sendRequest;
    window.notifyCenter=openFriendCenter;
    window.respondFriendProposalV249233=legacyRespond;
    window.respondFriendProposalV249223=legacyRespond;
    window.acceptContact=peer=>legacyByPeer(peer,true);
    window.rejectContact=peer=>legacyByPeer(peer,false);
    window.sendFriendProposal=sendRequest;
    Object.assign(window.ITH,{
      notifyCenter:openFriendCenter,
      respondFriendV249390:respond,
      respondFriendProposalV249233:legacyRespond,
      respondFriendProposalV249223:legacyRespond,
      acceptContact:peer=>legacyByPeer(peer,true),
      rejectContact:peer=>legacyByPeer(peer,false),
      sendFriendProposal:sendRequest,
      loadFriendNotificationsV249390:loadFriendItems,
      friendIdentityVersionV249390:VERSION,
    });
    document.documentElement.setAttribute('data-ithaki-friend-identity','V249390');
  }
  function install(){ensureCss();installOverrides();[300,900,1800,3600].forEach(t=>setTimeout(installOverrides,t));window.addEventListener('focus',installOverrides);document.addEventListener('visibilitychange',()=>{if(!document.hidden)installOverrides()})}
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',install,{once:true});else install();
})();
