(function(){
  const endpoint = window.MJ_V304_NOTIFY_ENDPOINT || 'ajax/mj-v304-notifications.php';
  let lastTopId = 0;
  function qs(s){return document.querySelector(s)}
  function qsa(s){return Array.from(document.querySelectorAll(s))}
  async function api(action, data){
    const fd = new FormData(); fd.append('action', action);
    Object.keys(data||{}).forEach(k=>fd.append(k,data[k]));
    const res = await fetch(endpoint,{method:'POST',body:fd,credentials:'same-origin'});
    return await res.json();
  }
  function toast(n){
    let stack = qs('.mj-toast-stack');
    if(!stack){ stack=document.createElement('div'); stack.className='mj-toast-stack'; document.body.appendChild(stack); }
    const el=document.createElement('div'); el.className='mj-toast';
    el.innerHTML='<b>'+escapeHtml(n.title||'Notification')+'</b><div>'+escapeHtml(n.message||'')+'</div>';
    stack.appendChild(el); setTimeout(()=>el.remove(),6500);
  }
  function escapeHtml(v){return String(v||'').replace(/[&<>'"]/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','\'':'&#39;','"':'&quot;'}[c];});}
  function render(data, showToast){
    const count = qs('.mj-notify-count');
    if(count){ count.textContent=data.unread||0; count.style.display=(data.unread>0?'flex':'none'); }
    const list = qs('.mj-notify-list');
    if(list){
      if(!data.items || !data.items.length){ list.innerHTML='<div class="mj-empty">No notifications yet.</div>'; }
      else list.innerHTML=data.items.map(n=>'<a class="mj-notify-item '+(n.is_read==0?'unread':'')+'" href="'+escapeHtml(n.link||'#')+'" data-id="'+n.id+'"><b>'+escapeHtml(n.title)+'</b><span>'+escapeHtml(n.message||'')+'</span><span>'+escapeHtml(n.created_at||'')+'</span></a>').join('');
    }
    if(showToast && data.items && data.items[0] && Number(data.items[0].id)>lastTopId && lastTopId!==0){ toast(data.items[0]); }
    if(data.items && data.items[0]) lastTopId=Number(data.items[0].id);
  }
  async function load(showToast){ try{ render(await api('list',{}), showToast); }catch(e){} }
  document.addEventListener('click', function(e){
    const bell=e.target.closest('.mj-notify-bell');
    if(bell){ const p=qs('.mj-notify-panel'); if(p){p.classList.toggle('open'); load(false);} }
    const item=e.target.closest('.mj-notify-item');
    if(item && item.dataset.id){ api('read',{id:item.dataset.id}); }
    const all=e.target.closest('[data-mj-notify-readall]');
    if(all){ e.preventDefault(); api('read_all',{}).then(()=>load(false)); }
  });
  document.addEventListener('DOMContentLoaded', function(){ load(false); setInterval(()=>load(true), 45000); });
})();
