(function(){
  'use strict';

  function onReady(run){ if(document.readyState==='loading'){document.addEventListener('DOMContentLoaded',run);} else {run();} }

  function initProductSelects(context, cfg){
    if (typeof jQuery === 'undefined') return;
    var $ = jQuery;
    var $scope = context ? $(context) : $(document);
    var $selects = $scope.find('.spar-product-select:not([disabled])');
    if (!$selects.length) return;
    var options = {
      ajax: {
        url: (window.ajaxurl || (cfg && cfg.ajaxUrl) || ''),
        dataType: 'json',
        delay: 250,
        data: function (params) {
          return {
            action: 'spar_search_products',
            q: params.term,
            nonce: (cfg && cfg.searchProductsNonce) || ''
          };
        },
        processResults: function (data) {
          return { results: (data && data.data) || [] };
        },
        cache: true
      },
      placeholder: (cfg && cfg.i18n && cfg.i18n.searchProduct) || 'Search for a product...',
      minimumInputLength: 2,
      allowClear: true,
      width: '100%'
    };
    $selects.each(function(){
      var $sel = $(this);
      if ($sel.hasClass('select2-hidden-accessible')) {
        try { $sel.select2('destroy'); } catch(e) {}
        try { $sel.selectWoo('destroy'); } catch(e) {}
      }
      if (typeof $.fn.selectWoo === 'function') $sel.selectWoo(options);
      else if (typeof $.fn.select2 === 'function') $sel.select2(options);
    });
  }

  onReady(function(){
  var cfg = window.sparRewardsTab || {};
    var i18n = cfg.i18n || {};
  var rewardsPanel = document.getElementById('spar-rewards-settings-panel');
  var disabledNotice = document.getElementById('spar-rewards-disabled-notice');
  var vouchersToggle = document.getElementById('spar-rewards-vouchers-enabled');
  var vouchersLabel = document.querySelector('label[for="spar-rewards-vouchers-enabled"]');

    var didInitialSync = false;
    function syncRewardsPanelState(enabled){
      var hasJQ = typeof jQuery !== 'undefined';
      // Panel
      if (rewardsPanel){
        if (!didInitialSync){
          // First paint: no animation to avoid layout shift
          rewardsPanel.classList.toggle('spar-hidden', !enabled);
          rewardsPanel.style.display = enabled ? '' : 'none';
        } else if (hasJQ){
          var $panel = jQuery(rewardsPanel);
          if (enabled){
            $panel.stop(true,true).hide().removeClass('spar-hidden').slideDown(200, function(){ this.style.display=''; });
          } else {
            $panel.stop(true,true).slideUp(200, function(){ this.classList.add('spar-hidden'); this.style.display='none'; });
          }
        } else {
          // Fallback without jQuery
          rewardsPanel.classList.toggle('spar-hidden', !enabled);
          rewardsPanel.style.display = enabled ? '' : 'none';
        }
      }
      // Notice
      if (disabledNotice){
        if (!didInitialSync){
          disabledNotice.classList.toggle('spar-hidden', enabled);
          disabledNotice.style.display = enabled ? 'none' : '';
        } else if (hasJQ){
          var $notice = jQuery(disabledNotice);
          if (enabled){
            $notice.stop(true,true).slideUp(200, function(){ this.classList.add('spar-hidden'); this.style.display='none'; });
          } else {
            $notice.stop(true,true).hide().removeClass('spar-hidden').slideDown(200, function(){ this.style.display=''; });
          }
        } else {
          disabledNotice.classList.toggle('spar-hidden', enabled);
          disabledNotice.style.display = enabled ? 'none' : '';
        }
      }
      didInitialSync = true;
    }

    // Initial sync; if toggle not yet present, attempt delayed binding
    syncRewardsPanelState(!vouchersToggle || vouchersToggle.checked);
    document.addEventListener('change', function(event){
      var target = event.target;
      if (target && target.id === 'spar-rewards-vouchers-enabled') {
        syncRewardsPanelState(!!target.checked);
      }
    }, true);

    document.addEventListener('click', function(event){
      var target = event.target;
      if (target && target.id === 'spar-rewards-vouchers-enabled') {
        setTimeout(function(){
          syncRewardsPanelState(!!target.checked);
        }, 0);
      }
    }, true);

    var lastToggleState = vouchersToggle ? !!vouchersToggle.checked : null;

    if (vouchersToggle){
      vouchersToggle.addEventListener('change', function(){
        syncRewardsPanelState(!!this.checked);
      });
      vouchersToggle.addEventListener('input', function(){
        syncRewardsPanelState(!!this.checked);
      });
      vouchersToggle.addEventListener('click', function(){
        var toggle = this;
        setTimeout(function(){
          syncRewardsPanelState(!!toggle.checked);
        }, 0);
      });
    } else {
      // Retry a few times in case markup loads late
      var tries = 0;
      var retryBind = setInterval(function(){
        vouchersToggle = document.getElementById('spar-rewards-vouchers-enabled');
        if (vouchersToggle){
          clearInterval(retryBind);
          syncRewardsPanelState(!!vouchersToggle.checked);
          vouchersToggle.addEventListener('change', function(){
            syncRewardsPanelState(!!this.checked);
          });
          vouchersToggle.addEventListener('input', function(){
            syncRewardsPanelState(!!this.checked);
          });
          vouchersToggle.addEventListener('click', function(){
            var toggle = this;
            setTimeout(function(){
              syncRewardsPanelState(!!toggle.checked);
            }, 0);
          });
        } else if (++tries > 20){
          clearInterval(retryBind);
        }
      }, 200);
    }

    // Poll for state changes in case events are blocked elsewhere.
    setInterval(function(){
      var current = document.getElementById('spar-rewards-vouchers-enabled');
      if (!current) {
        return;
      }
      var checked = !!current.checked;
      if (lastToggleState === null) {
        lastToggleState = checked;
        return;
      }
      if (checked !== lastToggleState) {
        lastToggleState = checked;
        syncRewardsPanelState(checked);
      }
    }, 250);

    // Also listen to label clicks to ensure state reflects immediately
    if (vouchersLabel){
      vouchersLabel.addEventListener('click', function(){
        setTimeout(function(){
          var t = document.getElementById('spar-rewards-vouchers-enabled');
          if (t) syncRewardsPanelState(!!t.checked);
        }, 0);
      });
    }

    function updateAddRewardButton(){
      var addButton = document.getElementById('spar-add-reward');
      if (!addButton) return;
      addButton.disabled = false;
      addButton.title = '';
    }

    // Sanitise a URL for safe use inside an HTML attribute (href).
    // Only allows absolute http(s) URLs. Returns the URL HTML-attribute-encoded,
    // or an empty string if the scheme is not http(s).
    function sanitiseUrl(url){
      if (typeof url !== 'string') return '';
      var trimmed = url.replace(/^\s+|\s+$/g, '');
      if (!/^https?:\/\//i.test(trimmed)) return '';
      return trimmed.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    }

    function initTemplateCouponEditLinks(context) {
      var $ = (typeof jQuery !== 'undefined') ? jQuery : null;
      var scope = context || document;
      var selects = scope.querySelectorAll ? scope.querySelectorAll('.spar-reward-template-coupon') : [];
      if (!selects.length) return;
      Array.prototype.forEach.call(selects, function(select){
        // Derive the target link div from the select's id, e.g. spar-reward-template-coupon-0 -> spar-reward-template-coupon-link-0
        var targetId = select.id ? select.id.replace('spar-reward-template-coupon-', 'spar-reward-template-coupon-link-') : '';
        var target = targetId ? document.getElementById(targetId) : null;
        if (!target) return;
        function updateCreateBtn(){
          var createBtn = select.closest('.spar-field-group') ? select.closest('.spar-field-group').querySelector('.spar-create-template-coupon') : null;
          if (createBtn) {
            var wrapper = createBtn.parentNode;
            if (wrapper) {
              wrapper.style.display = (select.value && select.value !== '0') ? 'none' : '';
            }
          }
        }
        function updateLink(){
          var id = select.value;
          updateCreateBtn();
          if (!id || id === '0') {
            target.innerHTML = '<em>' + (i18n.templateCouponNoSelected || 'No template selected.') + '</em>';
            return;
          }
          target.innerHTML = '<em>' + (i18n.templateCouponLoading || 'Loading…') + '</em>';
          if (!$) return;
          $.ajax({
            url: (cfg.ajaxUrl || window.ajaxurl || ''),
            type: 'POST',
            dataType: 'json',
            data: {
              action: 'spar_get_coupon_edit_link',
              coupon_id: id,
              nonce: (cfg.couponEditLinkNonce || '')
            }
          }).done(function(resp){
            if (resp && resp.success && resp.data && resp.data.url) {
              var safeUrl  = sanitiseUrl(resp.data.url);
              var safeText = resp.data.text || 'Edit coupon';
              if (safeUrl) {
                target.innerHTML = '<a href="' + safeUrl + '" target="_blank" rel="noopener noreferrer">' + $('<div>').text(safeText).html() + '</a>';
              } else {
                target.innerHTML = '<em>' + $('<div>').text(safeText).html() + '</em>';
              }
            } else if (resp && resp.data && resp.data.text) {
              target.innerHTML = '<em>' + $('<div>').text(resp.data.text).html() + '</em>';
            } else {
              target.innerHTML = '<em>' + (i18n.templateCouponError || 'Error.') + '</em>';
            }
          }).fail(function(){
            target.innerHTML = '<em>' + (i18n.templateCouponError || 'Error.') + '</em>';
          });
        }
        select.addEventListener('change', updateLink);
        updateLink();
      });
    }

    // Init edit links for existing reward items
    initTemplateCouponEditLinks(null);

    // Delegated handler for "Enable Template Coupon" checkbox
    function handleTemplateCouponToggle(cb) {
      if (!cb || !cb.classList.contains('spar-enable-template-coupon')) return;
      var fieldGroup = cb.closest('.spar-field-group');
      if (!fieldGroup) return;
      var section = fieldGroup.nextElementSibling;
      if (!section || !section.classList.contains('spar-template-coupon-section')) return;
      if (cb.checked) {
        section.classList.remove('spar-hidden');
        section.style.display = '';
      } else {
        section.classList.add('spar-hidden');
        section.style.display = 'none';
      }
    }
    document.addEventListener('change', function(e){
      handleTemplateCouponToggle(e.target);
    });
    // Also handle click on the toggle slider/label in case change doesn't fire
    document.addEventListener('click', function(e){
      var slider = e.target.closest('.spar-toggle-switch');
      if (!slider) return;
      var cb = slider.querySelector('.spar-enable-template-coupon');
      if (!cb) return;
      // Use setTimeout so the checked state has updated before we read it
      setTimeout(function(){ handleTemplateCouponToggle(cb); }, 0);
    });

    // Delegated handler for "Create New Template" buttons
    document.addEventListener('click', function(e){
      var btn = e.target.closest('.spar-create-template-coupon');
      if (!btn) return;
      e.preventDefault();
      var $ = (typeof jQuery !== 'undefined') ? jQuery : null;
      if (!$) return;
      var rewardItem = btn.closest('.spar-reward-item');
      if (!rewardItem) return;
      var select = rewardItem.querySelector('.spar-reward-template-coupon');
      if (!select) return;
      btn.disabled = true;
      btn.textContent = i18n.creatingTemplate || 'Creating…';
      $.ajax({
        url: (cfg.ajaxUrl || window.ajaxurl || ''),
        type: 'POST',
        dataType: 'json',
        data: {
          action: 'spar_create_template_coupon',
          nonce: (cfg.createTemplateCouponNonce || '')
        }
      }).done(function(resp){
        if (resp && resp.success && resp.data) {
          var opt = document.createElement('option');
          opt.value = String(resp.data.coupon_id);
          opt.textContent = resp.data.coupon_title + ' (#' + resp.data.coupon_id + ')';
          select.appendChild(opt);
          select.value = String(resp.data.coupon_id);
          // Trigger change so the edit link updates
          var evt = document.createEvent('HTMLEvents');
          evt.initEvent('change', true, false);
          select.dispatchEvent(evt);
        } else {
          var msg = (resp && resp.data && typeof resp.data === 'string') ? resp.data : (i18n.templateCouponError || 'Error.');
          alert(msg);
        }
      }).fail(function(){
        alert(i18n.templateCouponError || 'Error.');
      }).always(function(){
        btn.disabled = false;
        btn.textContent = i18n.createNewTemplate || 'Create New Template';
      });
    });

    function updateFieldValidation(rewardItem){
      var typeSelect = rewardItem.querySelector('.reward-type-select');
      if (!typeSelect) return;
      var voucherSettings = rewardItem.querySelector('.spar-voucher-settings');
      var productSettings = rewardItem.querySelector('.spar-product-settings');
      var customSettings  = rewardItem.querySelector('.spar-custom-settings');
      var typeBadge = rewardItem.querySelector('.spar-reward-type-badge');
      // Reset visibility
      ['voucherSettings','productSettings','customSettings'].forEach(function(ref){ /* no-op placeholder */ });
      var showVoucher = typeSelect.value === 'voucher';
      var showProduct = typeSelect.value === 'product';
      var showCustom  = typeSelect.value === 'custom';
      if (voucherSettings) {
        voucherSettings.classList.toggle('spar-hidden', !showVoucher);
        voucherSettings.style.display = showVoucher ? '' : 'none';
      }
      if (productSettings) {
        productSettings.classList.toggle('spar-hidden', !showProduct);
        productSettings.style.display = showProduct ? '' : 'none';
      }
      if (customSettings) {
        customSettings.classList.toggle('spar-hidden', !showCustom);
        customSettings.style.display  = showCustom  ? '' : 'none';
      }
      if (typeBadge){
        if (showVoucher) typeBadge.textContent='🎟️';
        else if (showProduct) typeBadge.textContent='🎁';
        else if (showCustom) typeBadge.textContent='⚙️';
      }
      // Enable/disable required fields based on type
      var voucherAmountField = voucherSettings && voucherSettings.querySelector('input[name*="[voucher_amount]"]');
      var productSelect = productSettings && productSettings.querySelector('select[name*="[product_id]"]');
      var developerIdField = customSettings && customSettings.querySelector('input[name*="[developer_id]"]');
      if (voucherAmountField){
        if (showVoucher){ voucherAmountField.removeAttribute('disabled'); voucherAmountField.setAttribute('required','required'); }
        else { voucherAmountField.setAttribute('disabled','disabled'); voucherAmountField.removeAttribute('required'); }
      }
      if (productSelect){
        if (showProduct){ productSelect.removeAttribute('disabled'); productSelect.setAttribute('required','required'); }
        else { productSelect.setAttribute('disabled','disabled'); productSelect.removeAttribute('required'); }
      }
      if (developerIdField){
        if (showCustom){ developerIdField.removeAttribute('disabled'); }
        else { developerIdField.removeAttribute('required'); }
      }
    }

    // Initialize existing
    document.querySelectorAll('#spar-rewards-list .spar-reward-item').forEach(updateFieldValidation);
    if (typeof updateAddRewardButton === 'function') {} // no-op linter
    updateAddRewardButton();
    initProductSelects(null, cfg);

    // Add new reward
    var addBtn = document.getElementById('spar-add-reward');
    if (addBtn) addBtn.addEventListener('click', function(){
      var list = document.getElementById('spar-rewards-list');
      if (!list) return;
      var rewardIndex = list.querySelectorAll('.spar-reward-item').length;
      var rewardId = 'reward_' + Math.random().toString(36).substr(2,8);
      var html = ''+
      '<div class="spar-reward-item" data-index="'+rewardIndex+'">'+
        '<div class="spar-reward-header clickable-header">'+
          '<span class="spar-drag-handle dashicons dashicons-move" aria-label="Drag to reorder" title="Drag to reorder"></span>'+
          '<span class="spar-reward-type-badge">🎟️</span>'+
          '<h4>'+ (i18n.newReward || 'New Reward') +'</h4>'+
          '<div class="spar-reward-actions">'+
            '<button type="button" class="button spar-toggle-reward">'+(i18n.edit||'Edit')+'</button>'+
            '<button type="button" class="button spar-delete-reward">'+(i18n.delete||'Delete')+'</button>'+
          '</div>'+
        '</div>'+
        '<div class="spar-reward-content" style="display:block;">'+
          '<input type="hidden" name="rewards['+rewardIndex+'][id]" value="'+rewardId+'" />'+
          '<div class="spar-reward-row">'+
            '<div class="spar-reward-col">'+
              '<label>'+(i18n.rewardName||'Reward Name:')+'</label>'+
              '<input type="text" name="rewards['+rewardIndex+'][name]" value="" placeholder="'+(i18n.rewardNamePlaceholder||'$10 Off Voucher')+'" required />'+
            '</div>'+
            '<div class="spar-reward-col">'+
              '<label>'+(i18n.pointsRequired||'Points Required:')+'</label>'+
              '<input type="number" name="rewards['+rewardIndex+'][points]" value="" min="1" placeholder="100" required />'+
            '</div>'+
          '</div>'+
          '<div class="spar-reward-row">'+
            '<div class="spar-reward-col">'+
              '<label>'+(i18n.rewardType||'Reward Type:')+'</label>'+
              '<select name="rewards['+rewardIndex+'][type]" class="reward-type-select" required>'+
                '<option value="voucher">'+(i18n.voucher||'Discount Voucher/Coupon')+'</option>'+
                '<option value="product">'+(i18n.product||'Free Product')+'</option>'+
                '<option value="custom">'+(i18n.custom||'Custom (Developer Hook)')+'</option>'+
              '</select>'+
            '</div>'+
            '<div class="spar-reward-col">'+
              '<label>'+(i18n.status||'Status:')+'</label>'+
              '<select name="rewards['+rewardIndex+'][status]" required>'+
                '<option value="active">'+(i18n.active||'Active')+'</option>'+
                '<option value="inactive">'+(i18n.inactive||'Inactive')+'</option>'+
              '</select>'+
            '</div>'+
          '</div>'+
          '<div class="spar-voucher-settings">'+
            '<h5>'+(i18n.voucherSettings||'Voucher Settings')+'</h5>'+
            '<div class="spar-reward-row">'+
              '<div class="spar-reward-col">'+
                '<label>'+(i18n.voucherAmount||'Voucher Amount:')+'</label>'+
                '<input type="number" step="0.01" name="rewards['+rewardIndex+'][voucher_amount]" value="" min="0" placeholder="10.00" required />'+
              '</div>'+
              '<div class="spar-reward-col">'+
                '<label>'+(i18n.discountType||'Discount Type:')+'</label>'+
                '<select name="rewards['+rewardIndex+'][discount_type]">'+
                  '<option value="fixed_cart">'+(i18n.fixedAmount||'Fixed Amount')+'</option>'+
                  '<option value="percent">'+(i18n.percentage||'Percentage')+'</option>'+
                '</select>'+
              '</div>'+
            '</div>'+
          '<div class="spar-field-group">'+
            '<label class="spar-toggle-label" style="display:flex; align-items:center; gap:8px;">'+
              '<input type="checkbox" name="rewards['+rewardIndex+'][free_shipping]" value="1" />'+
              '<span>'+(i18n.freeShipping||'Free Shipping')+'</span>'+
            '</label>'+
          '</div>'+
          '</div>'+
          '<div class="spar-product-settings" style="display:none;">'+
            '<h5>'+(i18n.productSettings||'Product Settings')+'</h5>'+
            '<div class="spar-reward-row">'+
              '<div class="spar-reward-col">'+
                '<label>'+(i18n.productLabel||'Product:')+'</label>'+
                '<select name="rewards['+rewardIndex+'][product_id]" class="spar-product-select" style="width:100%;" disabled></select>'+
                '<small>'+(i18n.productHelp||'Search and select a WooCommerce product for the free product reward')+'</small>'+
              '</div>'+
            '</div>'+
          '</div>'+
          '<div class="spar-field-group">'+
            '<label>'+(i18n.expiryDate||'Expiry Date:')+'</label>'+
            '<input type="date" name="rewards['+rewardIndex+'][expiry_date]" value="" style="width:200px;" />'+
          '</div>'+
          '<div class="spar-field-group">'+
            '<label class="spar-toggle-label" style="display:flex;align-items:center;gap:8px;">'+
              '<div class="spar-toggle-switch">'+
                '<input type="checkbox" class="spar-enable-template-coupon" />'+
                '<span class="spar-toggle-slider"></span>'+
              '</div>'+
              (i18n.enableTemplateCoupon||'Enable Template Coupon')+
            '</label>'+
          '</div>'+
          '<div class="spar-template-coupon-section spar-hidden">'+
            '<div class="spar-field-group">'+
              '<label>'+(i18n.templateCoupon||'Template Coupon (optional):')+'</label>'+
              '<select name="rewards['+rewardIndex+'][template_coupon_id]" id="spar-reward-template-coupon-'+rewardIndex+'" class="spar-reward-template-coupon spar-minw-280">'+
                '<option value="0">'+(i18n.templateCouponNone||'No template \u2013 use basic settings above')+'</option>'+
              '</select>'+
              '<small>'+(i18n.templateCouponHelp||'Select an existing coupon to use as a template. All coupon settings will be copied to the generated voucher.')+'</small>'+
              '<div style="margin-top:6px;"><button type="button" class="button button-secondary spar-create-template-coupon" data-index="'+rewardIndex+'">'+(i18n.createNewTemplate||'Create New Template')+'</button></div>'+
              '<div id="spar-reward-template-coupon-link-'+rewardIndex+'" class="spar-my-5"><em>'+(i18n.templateCouponNoSelected||'No template selected.')+'</em></div>'+
            '</div>'+
          '</div>'+
          '<div class="spar-custom-settings" style="display:none;">'+
            '<h5>'+(i18n.customSettings||'Custom Reward Settings')+'</h5>'+
            '<div class="spar-field-group">'+
              '<label>'+(i18n.customDesc||'Short Description:')+'</label>'+
              '<textarea name="rewards['+rewardIndex+'][custom_description]" rows="3" placeholder="'+(i18n.customDescPlaceholder||'Explain what this custom reward grants the user')+'" style="width:100%;"></textarea>'+
            '</div>'+
            '<div class="spar-field-group">'+
              '<label>'+(i18n.developerId||'Developer Reward ID:')+'</label>'+
              '<input type="text" name="rewards['+rewardIndex+'][developer_id]" value="" placeholder="reward_internal_key" pattern="[a-z0-9\-_]{3,60}" />'+
              '<small>'+(i18n.developerIdHelp||'Unique lowercase identifier used in spar_custom_reward_claimed hook.')+'</small>'+
            '</div>'+
          '</div>'+
        '</div>'+
      '</div>';
      list.insertAdjacentHTML('beforeend', html);
      var newItem = list.querySelector('.spar-reward-item[data-index="'+rewardIndex+'"]');
      if (newItem){ updateFieldValidation(newItem); initProductSelects(newItem, cfg); initTemplateCouponEditLinks(newItem); }
      updateAddRewardButton();
      // After adding, ensure sortable is aware of new item
      if (typeof jQuery !== 'undefined' && jQuery.fn.sortable) {
        jQuery('#spar-rewards-list').sortable('refresh');
      }
      if (typeof jQuery !== 'undefined') {
        jQuery('#spar-settings-form').trigger('spar-save-settings');
      }
    });

    // Delegated events
    var rewardsList = document.getElementById('spar-rewards-list');
    function toggleRewardContent(content, toggleBtn){
      if (!content) return;
      var isHidden = content.classList.contains('spar-hidden') || content.style.display === 'none';
      content.classList.toggle('spar-hidden', !isHidden);
      content.style.display = isHidden ? 'block' : 'none';
      if (toggleBtn) {
        toggleBtn.textContent = isHidden ? (i18n.close || 'Close') : (i18n.edit || 'Edit');
      }
    }

    if (rewardsList) rewardsList.addEventListener('click', function(e){
      if (e.target.closest('.spar-reward-header') && !e.target.closest('.spar-reward-actions') && !e.target.closest('.spar-drag-handle')){
        var header = e.target.closest('.spar-reward-header');
        var content = header.nextElementSibling;
        var toggleBtn = header.querySelector('.spar-toggle-reward');
        if (content && content.classList.contains('spar-reward-content')){
          toggleRewardContent(content, toggleBtn);
        }
        return;
      }
      if (e.target.classList.contains('spar-toggle-reward')){
        var content2 = e.target.closest('.spar-reward-item').querySelector('.spar-reward-content');
        toggleRewardContent(content2, e.target);
      }
      if (e.target.classList.contains('spar-delete-reward')){
        if (confirm(i18n.confirmDelete || 'Are you sure you want to delete this reward?')){
          e.target.closest('.spar-reward-item').remove();
          updateAddRewardButton();
          // Reindex after deletion to keep names tidy
          if (typeof reindexRewards === 'function') { reindexRewards(); }
          if (typeof jQuery !== 'undefined') {
            jQuery('#spar-settings-form').trigger('spar-save-settings');
          }
        }
      }
    });

    if (rewardsList) rewardsList.addEventListener('input', function(e){
      if (e.target.name && e.target.name.indexOf('[name]') !== -1){
        var header = e.target.closest('.spar-reward-item').querySelector('.spar-reward-header h4');
        if (header) header.textContent = e.target.value || (i18n.untitledReward || 'Untitled Reward');
      }
    });

    if (rewardsList) rewardsList.addEventListener('change', function(e){
      if (e.target.classList.contains('reward-type-select')){
        var rewardItem = e.target.closest('.spar-reward-item');
        updateFieldValidation(rewardItem);
        if (e.target.value === 'product') initProductSelects(rewardItem, cfg);
      }
    });

    function reindexRewards(){
      var list = document.getElementById('spar-rewards-list');
      if (!list) return;
      var items = list.querySelectorAll('.spar-reward-item');
      items.forEach(function(item, newIndex){
        // Update data-index
        item.setAttribute('data-index', String(newIndex));
        // Update all name attributes from rewards[<old>][field] to rewards[newIndex][field]
    var fields = item.querySelectorAll('input[name^="rewards["], select[name^="rewards["], textarea[name^="rewards["]');
        fields.forEach(function(field){
          var name = field.getAttribute('name');
          if (!name) return;
          var newName = name.replace(/rewards\[(?:\d+)\]/, 'rewards['+ newIndex +']');
          field.setAttribute('name', newName);
        });
        // Update any IDs that include the old index (currently free shipping checkbox)
        var fs = item.querySelector('input[id^="spar-free-shipping-"]');
        var label = item.querySelector('label[for^="spar-free-shipping-"]');
        if (fs){
          fs.id = 'spar-free-shipping-' + newIndex;
        }
        if (label){
          label.setAttribute('for', 'spar-free-shipping-' + newIndex);
        }
      });
    }

    function initSortable(){
      if (typeof jQuery === 'undefined') return;
      var $ = jQuery;
      if (!$.fn.sortable) return;
      var $list = $('#spar-rewards-list');
      if (!$list.length) return;
      try {
        $list.sortable({
          items: '.spar-reward-item',
          handle: '.spar-drag-handle',
          tolerance: 'pointer',
          axis: 'y',
          containment: 'parent',
          placeholder: 'spar-reward-sortable-placeholder',
          forcePlaceholderSize: true,
          update: function(){
            reindexRewards();
            if (typeof jQuery !== 'undefined') {
              jQuery('#spar-settings-form').trigger('spar-save-settings');
            }
          }
        });
      } catch(e) { /* no-op */ }
    }

    // Init sortable after DOM ready
    initSortable();

    var settingsForm = document.querySelector('form[method="post"]');
    if (settingsForm) settingsForm.addEventListener('submit', function(){
      // Ensure consistent naming order before submit
      reindexRewards();
      var disabledFields = document.querySelectorAll('#spar-rewards-list select[disabled], #spar-rewards-list input[disabled]');
      disabledFields.forEach(function(field){ field.removeAttribute('disabled'); field.setAttribute('data-was-disabled','true'); });
      setTimeout(function(){
        disabledFields.forEach(function(field){ if (field.hasAttribute('data-was-disabled')){ field.setAttribute('disabled','disabled'); field.removeAttribute('data-was-disabled'); } });
      }, 100);
    });
  });
})();
