'use strict';
(function(){
  var U = window.KNSDD_Utils || {};

  function updateContainer(el, html){
    if(!el) return;
    el.innerHTML = html || '';
    try{
      el.setAttribute('data-content-ready','1');
      // Force modu KAPALIYSA, görünürlüğü burada tamamla (relocator yüklenmez)
      var isForce = !!(window.KNSDD_MsgReloc && window.KNSDD_MsgReloc.force);
      if(!isForce){
        el.setAttribute('data-ready','1');
        try{ el.style.removeProperty('display'); }catch(__){ try{ el.style.display=''; }catch(___){ } }
      }
    }catch(_){ }
    try{ document.dispatchEvent(new CustomEvent('knsdd:promo-content-ready', { detail: { el: el } })); }catch(_){ }
  }

  // ready/delay/fetchWithTimeout utils üzerinden kullanılacak

  // Aynı konteyner için çift istek önleme
  var loadingSet = typeof WeakSet !== 'undefined' ? new WeakSet() : null;

  function fetchPromo(container){
    try{
      if(loadingSet){
        if(loadingSet.has(container)) return; // zaten istek atılıyor
        loadingSet.add(container);
      } else {
        if(container.getAttribute('data-knsdd-loading') === '1') return;
        container.setAttribute('data-knsdd-loading', '1');
      }

      // Offline ise boş bırak ve sessizce çık
      if(typeof navigator !== 'undefined' && 'onLine' in navigator && !navigator.onLine){
        updateContainer(container, '');
        return;
      }

      var pid = parseInt(container.getAttribute('data-product-id'), 10) || 0;
      if(!pid) { updateContainer(container, ''); return; }

      var fd = new FormData();
      fd.append('action', 'knsdd_get_product_promo');
      fd.append('product_id', String(pid));
      fd.append('nonce', (window.KNSDD_Promo && KNSDD_Promo.nonce) ? KNSDD_Promo.nonce : '');
      var url = (window.KNSDD_Promo && KNSDD_Promo.ajax_url) ? window.KNSDD_Promo.ajax_url : '/wp-admin/admin-ajax.php';

      var maxAttempts = 3; // 1 + 2 retry
      var attempt = 0;

      function attemptOnce(){
        attempt++;
        return U.fetchWithTimeout(url, { method: 'POST', body: fd, credentials: 'same-origin' }, 3000)
          .then(function(r){ return r.json(); })
          .then(function(res){
            if(res && res.success && res.data){
              updateContainer(container, res.data.html || '');
              return true;
            }
            // başarısız durum
            return false;
          })
          .catch(function(){ return false; });
      }

      (function run(){
        attemptOnce().then(function(ok){
          if(ok){ return done(); }
          if(attempt >= maxAttempts){ return done(); }
          // exponential backoff + küçük jitter
          var backoff = Math.pow(2, attempt - 1) * 800; // 800, 1600
          var jitter = Math.floor(Math.random() * 120); // ±120ms
          U.delay(backoff + jitter).then(run);
        });
      })();

      function done(){
        // son durumda başarı yoksa konteyner boş kalır (sessiz düşme)
        if(loadingSet){ loadingSet.delete(container); }
        else { container.removeAttribute('data-knsdd-loading'); }
      }
    } catch(e){
      updateContainer(container, '');
      if(loadingSet){ loadingSet.delete(container); }
      else { container.removeAttribute('data-knsdd-loading'); }
    }
  }

  U.ready(function(){
    var containers = document.querySelectorAll('.knsdd-product-promo[data-product-id]');
    if(!containers || !containers.length) return;
    containers.forEach(function(c){ fetchPromo(c); });
  });
  
  // Relocator sonradan konteyner oluşturursa yakala ve doldur
  try{
    document.addEventListener('knsdd:promo-container-added', function(ev){
      try{
        var el = ev && ev.detail && ev.detail.el;
        if(el && el.matches && el.matches('.knsdd-product-promo[data-product-id]')){
          fetchPromo(el);
        }
      }catch(_){ }
    });
  }catch(_){ }
  
  // Ek güvence: MutationObserver ile dinle (hafif)
  try{
    var target = document.body;
    if(target && 'MutationObserver' in window){
      var obs = new MutationObserver(function(muts){
        for(var i=0;i<muts.length;i++){
          var m = muts[i];
          if(m.addedNodes && m.addedNodes.length){
            for(var j=0;j<m.addedNodes.length;j++){
              var n = m.addedNodes[j];
              try{
                if(n.nodeType === 1){
                  if(n.matches && n.matches('.knsdd-product-promo[data-product-id]')){ fetchPromo(n); }
                  var found = n.querySelectorAll ? n.querySelectorAll('.knsdd-product-promo[data-product-id]') : [];
                  if(found && found.length){ found.forEach(function(c){ fetchPromo(c); }); }
                }
              }catch(_){ }
            }
          }
        }
      });
      obs.observe(target, { childList:true, subtree:true });
    }
  }catch(_){ }
})();
