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

  function setHTML(el, html){ if(!el) return; el.innerHTML = html || ''; }

  // fetchWithTimeout utils üzerinden kullanılacak

  var inFlight = typeof WeakMap !== 'undefined' ? new WeakMap() : null;
  var timers = typeof WeakMap !== 'undefined' ? new WeakMap() : null;

  function schedule(container, fn, wait){
    if(!timers) return fn();
    var t = timers.get(container); if(t){ clearTimeout(t); }
    var id = setTimeout(fn, wait || 0); timers.set(container, id);
  }

  function postTierHTML(container, productId){
    try{
      if(!productId){ setHTML(container, ''); return; }
      if(inFlight){ if(inFlight.get(container) === productId){ return; } inFlight.set(container, productId); }

      // offline
      if(typeof navigator !== 'undefined' && 'onLine' in navigator && !navigator.onLine){ setHTML(container, ''); return; }

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

      U.fetchWithTimeout(url, { method: 'POST', body: fd, credentials: 'same-origin' }, 3500)
        .then(function(r){ return r.json(); })
        .then(function(res){
          if(res && res.success && res.data){ setHTML(container, res.data.html || ''); }
          else { setHTML(container, ''); }
        })
        .catch(function(){ setHTML(container, ''); })
        .finally(function(){ if(inFlight){ inFlight.delete(container); } });
    } catch(e){ setHTML(container, ''); if(inFlight){ inFlight.delete(container); } }
  }

  function getSelectedVariationId($form){
    var $input = $form.find('input.variation_id');
    if($input && $input.length){ var vid = parseInt($input.val(), 10); return isNaN(vid) ? 0 : vid; }
    return 0;
  }

  function bindVariationEvents(container){
    var $container = $(container);
    // En yakın ürün formunu bul
    var $form = $container.closest('.product').find('form.cart').first();
    if(!$form || !$form.length) return;

    var parentId = parseInt($container.attr('data-parent-id'), 10) || 0;

    function refresh(){
      var vid = getSelectedVariationId($form);
      var pid = vid || (parseInt($container.attr('data-product-id'), 10) || parentId);
      schedule(container, function(){ postTierHTML(container, pid); }, 120);
    }

    // İlk yükleme
    refresh();

    // WooCommerce varyasyon event'leri
    $form.on('found_variation', function(_e, variation){
      var vid = variation && variation.variation_id ? parseInt(variation.variation_id, 10) : 0;
      postTierHTML(container, vid || parentId);
    });
    $form.on('reset_data hide_variation', function(){ postTierHTML(container, parentId); });
    $form.on('woocommerce_variation_has_changed', function(){ refresh(); });
    $form.on('change', 'input.variation_id', function(){ refresh(); });
  }

  U.ready(function(){
    if(typeof window.jQuery === 'undefined') return; // güvenli çıkış
    var nodes = document.querySelectorAll('.knsdd-tier-table-container[data-product-id]');
    if(!nodes || !nodes.length) return;
    nodes.forEach(function(el){
      // Varyasyon ürünlerde bind; basit üründe de ilk yükleme
      bindVariationEvents(el);
      if(!el.closest('.product') || !jQuery(el).closest('.product').find('form.cart.variations_form').length){
        // basit ürün veya varyasyon formu yok -> parent id ile yükle
        var pid = parseInt(el.getAttribute('data-product-id'), 10) || 0;
        if(pid) postTierHTML(el, pid);
      }
    });
  });

  // Dinamik olarak eklenen konteynerler için (ör: relocator ensureContainer)
  try{
    document.addEventListener('knsdd:tier-container-added', function(ev){
      var detail = ev && ev.detail ? ev.detail : {};
      var el = detail.el || null;
      if(!el) return;
      // bind ve ilk içerik yüklemesi
      bindVariationEvents(el);
      var pid = parseInt(el.getAttribute('data-product-id'), 10) || (detail.productId || 0);
      if(pid) postTierHTML(el, pid);
    });
  } catch(_e){}
})(window.jQuery);
