(function(){
  var base=(window.MJ_BASE_URL||'').replace(/\/$/,'');
  if(!base) return;
  var originalTitle=document.title;
  var lastKey='mj_last_chat_overlay_id';
  var lastId=parseInt(localStorage.getItem(lastKey)||'0',10)||0;
  var currentChat=window.MJ_CURRENT_CHAT_ID||0;
  var busy=false;
  function esc(s){ return String(s||'').replace(/[&<>"']/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];}); }
  function badge(n){
    document.querySelectorAll('[data-mj-chat-unread-count]').forEach(function(el){ el.textContent=n>99?'99+':String(n||0); el.style.display=n>0?'':'none'; });
    if(n>0){ document.title='('+n+') '+originalTitle.replace(/^\(\d+\)\s*/,''); } else { document.title=originalTitle.replace(/^\(\d+\)\s*/,''); }
  }
  function ensureBox(){
    var box=document.getElementById('mjChatOverlayBox');
    if(!box){ box=document.createElement('div'); box.id='mjChatOverlayBox'; box.className='mj-chat-overlay-box'; document.body.appendChild(box); }
    return box;
  }
  window.mjOverlayToast=function(title,msg,type){
    var box=ensureBox();
    var card=document.createElement('div'); card.className='mj-chat-toast small-toast '+(type||'');
    card.innerHTML='<div class="mj-chat-toast-icon"><i class="bi bi-info-circle"></i></div><div class="mj-chat-toast-body"><b>'+esc(title)+'</b><p>'+esc(msg||'')+'</p></div><button type="button" class="mj-chat-toast-close">×</button>';
    box.appendChild(card);
    card.querySelector('.mj-chat-toast-close').onclick=function(){card.remove();};
    setTimeout(function(){card.remove();},5500);
  };
  function show(items){
    if(!items || !items.length) return;
    var box=ensureBox();
    if(items.length>1){
      var max=items.reduce(function(m,x){return Math.max(m,Number(x.message_id||0));},lastId);
      var url=base+'/messages.php';
      var card=document.createElement('a'); card.href=url; card.className='mj-chat-toast';
      card.innerHTML='<div class="mj-chat-toast-icon"><i class="bi bi-chat-dots"></i></div><div class="mj-chat-toast-body"><b>'+items.length+' new messages</b><p>Tap to open your message inbox.</p></div><span class="mj-chat-toast-action">Open</span>';
      box.appendChild(card); setTimeout(function(){card.remove();},7000); lastId=max; localStorage.setItem(lastKey,String(lastId)); return;
    }
    var it=items[0];
    if(Number(it.message_id||0)<=lastId) return;
    lastId=Number(it.message_id||0); localStorage.setItem(lastKey,String(lastId));
    var a=document.createElement('a'); a.href=it.url||base+'/messages.php'; a.className='mj-chat-toast';
    a.innerHTML='<img src="'+esc(it.image||'')+'" alt=""><div class="mj-chat-toast-body"><b>New message from '+esc(it.title||'User')+'</b><span>'+esc(it.subtitle||'Marketplace chat')+'</span><p>'+esc(it.message||'Open chat to view message.')+'</p></div><span class="mj-chat-toast-action">Open</span><button type="button" class="mj-chat-toast-close">×</button>';
    a.querySelector('.mj-chat-toast-close').onclick=function(e){e.preventDefault();e.stopPropagation();a.remove();};
    box.appendChild(a); setTimeout(function(){a.remove();},7500);
  }
  function poll(){
    if(busy) return; busy=true;
    fetch(base+'/ajax/live-chat-notifications.php?since_id='+encodeURIComponent(lastId)+'&current_chat_id='+encodeURIComponent(currentChat),{credentials:'same-origin'})
      .then(function(r){return r.json().catch(function(){return {ok:false};});})
      .then(function(res){ busy=false; if(!res || !res.ok || res.logged_in===false) return; badge(Number(res.unread_count||0)); show(res.items||[]); if(res.max_id && Number(res.max_id)>lastId && !(res.items||[]).length){ lastId=Number(res.max_id); localStorage.setItem(lastKey,String(lastId)); } })
      .catch(function(){busy=false;});
  }
  document.addEventListener('DOMContentLoaded',function(){ poll(); setInterval(poll, 8000); });
})();
