(function(){
  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};});});
  }
  window.mjTrackListingEvent=function(id,type,value){
    if(!id) return; post((window.MJ_BASE_URL||'') + '/ajax/track-share.php',{listing_id:id,event_type:type,event_value:value||''}).catch(function(){});
  };
  window.mjTrackCompanyEvent=function(id,type,value){
    if(!id) return; post((window.MJ_BASE_URL||'') + '/ajax/track-company.php',{company_id:id,event_type:type,event_value:value||''}).catch(function(){});
  };
  function mjToggleSave(btn){
    var type=btn.getAttribute('data-mj-save'), id=btn.getAttribute('data-save-id');
    if(!type || !id) return;
    btn.disabled=true;
    post((window.MJ_BASE_URL||'') + '/ajax/save-item.php',{type:type,id:id,action:'toggle'}).then(function(res){
      btn.disabled=false;
      if(!res || !res.ok){ mjToast('Please login', (res && res.error) ? res.error : 'Unable to save this item.', 'warning'); return; }
      btn.setAttribute('data-saved', res.saved ? '1' : '0');
      btn.classList.toggle('btn-success', !!res.saved);
      btn.classList.toggle('btn-outline-success', !res.saved);
      var icon=btn.querySelector('i');
      if(icon){ icon.className='bi ' + (res.saved ? 'bi-heart-fill' : 'bi-heart') + ' me-1'; }
      var span=btn.querySelector('span');
      if(span){ span.textContent = (res.saved ? 'Saved ' : 'Save ') + (type==='company' ? 'Company' : 'Listing'); }
      mjToast(res.saved ? 'Saved' : 'Removed', res.message || 'Updated saved items.', 'success');
    }).catch(function(){ btn.disabled=false; mjToast('Error','Unable to save this item now.','warning'); });
  };
  document.addEventListener('click',function(e){
    var save=e.target.closest('[data-mj-save]'); if(save){ e.preventDefault(); mjToggleSave(save); return; }
    var c=e.target.closest('[data-mj-company-track]'); if(c){ window.mjTrackCompanyEvent(c.getAttribute('data-company-id'), c.getAttribute('data-mj-company-track'), c.getAttribute('data-listing-id')||''); }
    var a=e.target.closest('[data-mj-track]'); if(a){ window.mjTrackListingEvent(a.getAttribute('data-listing-id'), a.getAttribute('data-mj-track'), a.getAttribute('data-share-type')||''); }
    var img=e.target.closest('[data-gallery-src]'); if(img){
      e.preventDefault();
      var all=[].slice.call(document.querySelectorAll('[data-gallery-src]')).map(function(x){return x.getAttribute('data-gallery-src');});
      var start=all.indexOf(img.getAttribute('data-gallery-src')); if(start<0) start=0; openGallery(all,start,img.getAttribute('data-gallery-title')||'Listing image');
    }
    var copy=e.target.closest('[data-copy-link]'); if(copy){ e.preventDefault(); var url=copy.getAttribute('data-copy-link'); navigator.clipboard&&navigator.clipboard.writeText(url); mjToast('Link copied','You can paste and share this listing.','success'); }
    var native=e.target.closest('[data-native-share]'); if(native){ e.preventDefault(); var url=native.getAttribute('data-url'), title=native.getAttribute('data-title')||document.title; if(navigator.share){navigator.share({title:title,url:url}).catch(function(){});} else { navigator.clipboard&&navigator.clipboard.writeText(url); mjToast('Link copied','Share it anywhere.','success');} }
  });
  function openGallery(images,index,title){
    if(!images.length) return; var current=index;
    var modal=document.getElementById('mjGalleryModal');
    if(!modal){
      var div=document.createElement('div'); div.innerHTML='<div class="modal fade" id="mjGalleryModal" tabindex="-1"><div class="modal-dialog modal-xl modal-dialog-centered"><div class="modal-content bg-dark text-white rounded-4 overflow-hidden"><div class="modal-header border-0"><h5 class="modal-title"></h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body text-center position-relative"><button class="btn btn-light position-absolute start-0 top-50 translate-middle-y ms-3 mj-prev">‹</button><img class="mj-gallery-img img-fluid rounded-3" style="max-height:75vh;object-fit:contain"><button class="btn btn-light position-absolute end-0 top-50 translate-middle-y me-3 mj-next">›</button><div class="small text-white-50 mt-2 mj-count"></div></div></div></div></div>'; document.body.appendChild(div.firstChild); modal=document.getElementById('mjGalleryModal');
      modal.querySelector('.mj-prev').onclick=function(){show(current-1)}; modal.querySelector('.mj-next').onclick=function(){show(current+1)};
    }
    function show(i){ current=(i+images.length)%images.length; modal.querySelector('.mj-gallery-img').src=images[current]; modal.querySelector('.modal-title').textContent=title; modal.querySelector('.mj-count').textContent=(current+1)+' / '+images.length; }
    show(current); new bootstrap.Modal(modal).show();
  }
  function mjToast(title,msg,type){
    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>'+escapeHtml(title)+'</b><br><span class="small text-muted">'+escapeHtml(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();},6000);
  }
  function escapeHtml(s){return String(s).replace(/[&<>'"]/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','\'':'&#39;','"':'&quot;'}[c];});}
})();
