(function(){
  function base(){ return (window.MJ_BASE_URL||'').replace(/\/$/,''); }
  function post(url, data){
    var fd = new FormData();
    Object.keys(data||{}).forEach(function(k){ fd.append(k, data[k]); });
    return fetch(url,{method:'POST',body:fd,credentials:'same-origin'}).then(function(r){return r.json().catch(function(){return {ok:false,error:'Invalid response'};});});
  }
  function get(url){ return fetch(url,{credentials:'same-origin'}).then(function(r){return r.json().catch(function(){return {ok:false};});}); }
  function esc(s){ return String(s||'').replace(/[&<>"']/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];}); }
  function toast(title,msg,type){
    if(window.mjOverlayToast){ window.mjOverlayToast(title,msg,type); return; }
    var box=document.getElementById('mjLiveToastBox');
    if(!box){ box=document.createElement('div'); box.id='mjLiveToastBox'; box.className='toast-container position-fixed bottom-0 end-0 p-3'; box.style.zIndex='1080'; document.body.appendChild(box); }
    var el=document.createElement('div'); el.className='toast align-items-center border-0 show';
    el.innerHTML='<div class="d-flex"><div class="toast-body"><b>'+esc(title)+'</b><br><span class="small text-muted">'+esc(msg)+'</span></div><button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast"></button></div>';
    box.appendChild(el); setTimeout(function(){el.remove();},5000);
  }
  function risky(text){ return /\b(otp|password|bank login|singpass|deposit outside|outside payment|transfer now|crypto|urgent deposit)\b/i.test(text||''); }
  function bubble(m){
    var row=document.createElement('div'); row.className='mj-chat-row '+(m.is_me?'is-me':'is-other'); row.setAttribute('data-message-id', m.id);
    row.innerHTML='<div class="mj-chat-bubble"><div class="mj-chat-name">'+esc(m.sender_name || (m.is_me?'Me':'User'))+'</div><div>'+String(m.message_html||esc(m.message||''))+'</div>'+(Number(m.risk_score||0)>0?'<div class="mj-risk-note"><i class="bi bi-exclamation-triangle me-1"></i>Safety warning detected</div>':'')+'<small>'+esc(m.time_label||m.created_at||'')+(m.is_me?' · '+(m.is_read?'Read':'Sent'):'')+'</small></div>';
    return row;
  }
  function scrollToEnd(box){ if(box){ box.scrollTop = box.scrollHeight; } }
  function updateBadge(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';
    });
  }
  function initChat(){
    var form=document.getElementById('mjChatForm');
    var box=document.getElementById('mjChatMessages');
    if(!form || !box || !form.getAttribute('data-realtime-chat')) return;
    var input=document.getElementById('mjChatMessageInput');
    var chatId=form.getAttribute('data-chat-id') || box.getAttribute('data-chat-id');
    var lastId=parseInt(box.getAttribute('data-last-id') || window.MJ_CHAT_LAST_ID || '0',10) || 0;
    var polling=false;
    function removeEmpty(){ var empty=box.querySelector('.mj-chat-empty'); if(empty) empty.remove(); }
    function appendMessages(messages){
      if(!messages || !messages.length) return;
      removeEmpty();
      messages.forEach(function(m){
        if(box.querySelector('[data-message-id="'+m.id+'"]')) return;
        box.appendChild(bubble(m));
        lastId=Math.max(lastId, parseInt(m.id,10)||0);
      });
      box.setAttribute('data-last-id', lastId);
      scrollToEnd(box);
    }
    function fetchNew(){
      if(polling) return; polling=true;
      get(base()+'/ajax/chat-fetch.php?chat_id='+encodeURIComponent(chatId)+'&after_id='+encodeURIComponent(lastId)).then(function(res){
        polling=false;
        if(res && res.ok){ appendMessages(res.messages||[]); updateBadge(Number(res.unread_count||0)); }
      }).catch(function(){ polling=false; });
    }
    form.addEventListener('submit',function(e){
      e.preventDefault();
      var msg=(input && input.value || '').trim();
      if(!msg){ if(input) input.focus(); toast('Type a message','Please type a message before sending.','warning'); return; }
      if(msg.length>2000){ toast('Message too long','Please keep it under 2000 characters.','warning'); return; }
      if(risky(msg) && !confirm('For your safety, never share OTP, passwords or bank login details. Do you still want to send this message?')){ return; }
      var btn=form.querySelector('button[type="submit"],button:not([type])');
      if(btn){ btn.disabled=true; btn.dataset.oldText=btn.innerHTML; btn.innerHTML='<span class="spinner-border spinner-border-sm me-1"></span>Sending'; }
      var data={}; new FormData(form).forEach(function(v,k){data[k]=v;});
      post(base()+'/ajax/chat-send.php', data).then(function(res){
        if(btn){ btn.disabled=false; btn.innerHTML=btn.dataset.oldText||'Send'; }
        if(!res || !res.ok){ toast('Message not sent', (res&&res.error)||'Please try again.','warning'); return; }
        if(input) input.value='';
        appendMessages([res.message]);
        updateBadge(Number(res.unread_count||0));
      }).catch(function(){ if(btn){ btn.disabled=false; btn.innerHTML=btn.dataset.oldText||'Send'; } toast('Network error','Please try again.','warning'); });
    }, true);
    document.querySelectorAll('.mj-quick-msg').forEach(function(btn){ btn.addEventListener('click',function(){ if(input){ input.value=this.textContent.trim(); input.focus(); } }); });
    document.addEventListener('click',function(e){
      var act=e.target.closest('[data-chat-action]'); if(!act) return;
      e.preventDefault();
      var action=act.getAttribute('data-chat-action');
      var cid=act.getAttribute('data-chat-id') || chatId;
      var token=(form.querySelector('[name="csrf_token"]')||{}).value || '';
      post(base()+'/ajax/chat-action.php',{chat_id:cid,action:action,csrf_token:token}).then(function(res){ toast(res && res.ok ? 'Updated' : 'Action failed', (res&&(res.message||res.error))||'Please try again.', res&&res.ok?'success':'warning'); });
    });
    scrollToEnd(box);
    setInterval(fetchNew, 3000);
    setTimeout(fetchNew, 1200);
  }
  document.addEventListener('DOMContentLoaded', initChat);
})();
