(function(){
  var seen={}; var initialized=false; var pollMs=Math.max(30000, Number(window.MJ_NOTIFICATION_POLL_MS||25000));
  try{seen=JSON.parse(sessionStorage.getItem('mj429_seen_notifications')||'{}')||{};}catch(e){seen={};}
  function saveSeen(){try{var keys=Object.keys(seen).slice(-250);var o={};keys.forEach(function(k){o[k]=seen[k];});seen=o;sessionStorage.setItem('mj429_seen_notifications',JSON.stringify(seen));}catch(e){}}
  function base(){return (window.MJ_BASE_URL||'').replace(/\/$/,'');}
  function endpoint(){return window.MJ_V304_NOTIFY_ENDPOINT || (base() + '/ajax/mj-v3041-notifications.php');}
  function esc(s){return String(s||'').replace(/[&<>"']/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];});}
  function wrap(){var w=document.querySelector('.mj-v3041-toast-wrap'); if(!w){w=document.createElement('div');w.className='mj-v3041-toast-wrap';document.body.appendChild(w);} return w;}
  function toast(item){
    if(!item) return; var key=item.dedupe_key||item.notification_key||item.id||((item.title||'')+'|'+(item.message||'')); if(seen[key]) return; seen[key]=Date.now(); saveSeen();
    var el=document.createElement('div'); el.className='mj-v3041-toast is-'+esc(item.type||'info');
    el.innerHTML='<button class="mj-v3041-toast-close" type="button">×</button><h4>'+esc(item.title||'Notification')+'</h4><p>'+esc(item.message||'')+'</p>'+(item.link?'<a href="'+esc(item.link)+'">Open now</a>':'');
    wrap().prepend(el); el.querySelector('button').onclick=function(){el.remove();}; setTimeout(function(){if(el&&el.parentNode)el.remove();},8500);
  }
  function setCount(sel,val){document.querySelectorAll(sel).forEach(function(el){el.textContent=val>99?'99+':val;el.style.display=val>0?'':'none';});}
  function normalizeItems(items){
    var by={}, out=[]; (items||[]).forEach(function(it){var key=it.dedupe_key||it.notification_key||it.id||((it.title||'')+'|'+(it.message||'')); if(by[key])return; by[key]=1; out.push(it);});
    var leads=out.filter(function(it){return /lead|enquiry/i.test((it.type||'')+' '+(it.title||''));});
    if(leads.length>1){return [{id:'lead-group-'+Date.now(),dedupe_key:'lead-group-'+leads.map(function(x){return x.id||x.dedupe_key;}).join('-'),title:leads.length+' new leads received',message:'Open your leads inbox to follow up.',type:'lead',link:(base()+'/leads.php')}].concat(out.filter(function(it){return !/lead|enquiry/i.test((it.type||'')+' '+(it.title||''));}));}
    return out;
  }
  function poll(first){fetch(endpoint(),{credentials:'same-origin'}).then(function(r){return r.json();}).then(function(data){if(!data||!data.ok)return;setCount('[data-mj-notification-count]',data.badges&&typeof data.badges.notifications!=='undefined'?data.badges.notifications:data.unread);if(data.badges){setCount('[data-mj-chat-unread-count]',data.badges.chat||0);setCount('[data-mj-leads-count]',data.badges.leads||0);}var items=normalizeItems((data.items||[]).filter(function(x){return !x.is_read;}));items.forEach(function(item){var key=item.dedupe_key||item.notification_key||item.id;if(first){seen[key]=Date.now();}else{toast(item);}});if(first)saveSeen();initialized=true;}).catch(function(){});}
  function interval(){return document.hidden?90000:pollMs;}
  var timer=null; function schedule(){clearInterval(timer);timer=setInterval(function(){poll(false);},interval());}
  document.addEventListener('visibilitychange',function(){schedule();if(!document.hidden)poll(false);});
  document.addEventListener('DOMContentLoaded',function(){poll(true);schedule();});
})();
