(function($){
  function updateWaitlistCount(wrapper,count){
    if(!wrapper || wrapper.dataset.showCount!=='1')return;
    var countNode=wrapper.querySelector('.stockbeacon-count');
    var textNode=wrapper.querySelector('.stockbeacon-count__text');
    if(!countNode || !textNode)return;
    var total=parseInt(count,10);
    if(!Number.isFinite(total) || total<=0){
      countNode.style.display='none';
      textNode.textContent='';
      return;
    }
    var singular=countNode.getAttribute('data-singular') || '%d person is waiting';
    var plural=countNode.getAttribute('data-plural') || '%d people are waiting';
    var tmpl=total===1?singular:plural;
    textNode.textContent=tmpl.replace('%d',String(total));
    countNode.style.display='';
  }

  if($){
    $(document).on('found_variation','.variations_form',function(e,v){
      var f=document.getElementById('stockbeacon-variation-form');
      if(!f)return;
      if(v&&v.stockbeacon_active){
        f.style.display='block';
        var w=f.querySelector('.stockbeacon-form-wrapper');
        if(w){
          w.dataset.variationId=String(v.variation_id||0);
          updateWaitlistCount(w,v.stockbeacon_count||0);
        }
      }else{
        f.style.display='none';
      }
    });
    $(document).on('reset_data','.variations_form',function(){
      var f=document.getElementById('stockbeacon-variation-form');
      if(f)f.style.display='none';
    });
  }
  document.addEventListener('DOMContentLoaded',function(){
    document.querySelectorAll('.stockbeacon-form-wrapper').forEach(function(wrapper){
      var countNode=wrapper.querySelector('.stockbeacon-count__text');
      if(!countNode)return;
      var matched=(countNode.textContent||'').match(/\d+/);
      updateWaitlistCount(wrapper,matched?matched[0]:0);
    });
    document.querySelectorAll('.stockbeacon-submit').forEach(function(b){
      b.addEventListener('click',handleSubmit);
    });
  });
})(window.jQuery);

function showMessage(wrapper,text,type){
  var m=wrapper.querySelector('.stockbeacon-message');
  if(!m)return;
  m.textContent=text;
  m.className='stockbeacon-message '+type;
  m.style.display='block';
}

function hideMessage(wrapper){
  var m=wrapper.querySelector('.stockbeacon-message');
  if(!m)return;
  m.style.display='none';
  m.textContent='';
}

function getSubmittingAriaLabel(){
  var i=stockbeaconData&&stockbeaconData.i18n;
  if(!i)return 'Submitting';
  return i.subscribing||i.submitting||'Submitting';
}

function setSubmitButtonIdle(btn){
  if(!btn)return;
  btn.classList.remove('stockbeacon-is-busy');
  btn.removeAttribute('aria-busy');
  btn.removeAttribute('aria-label');
  btn.style.minWidth='';
  btn.style.width='';
  btn.style.boxSizing='';
  btn.innerHTML='';
  btn.textContent=(stockbeaconData&&stockbeaconData.i18n&&stockbeaconData.i18n.button_text)?stockbeaconData.i18n.button_text:'Notify Me';
}

function setSubmitButtonSubmitting(btn){
  if(!btn)return;
  var w=Math.ceil(btn.getBoundingClientRect().width);
  if(!w||!isFinite(w))w=112;
  btn.style.boxSizing='border-box';
  btn.style.minWidth=w+'px';
  btn.style.width=w+'px';
  btn.classList.add('stockbeacon-is-busy');
  btn.setAttribute('aria-busy','true');
  btn.setAttribute('aria-label',getSubmittingAriaLabel());
  btn.innerHTML='';
  var inner=document.createElement('span');
  inner.className='stockbeacon-submit__inner';
  var spin=document.createElement('span');
  spin.className='stockbeacon-submit__spinner';
  spin.setAttribute('aria-hidden','true');
  inner.appendChild(spin);
  btn.appendChild(inner);
}

function setFormSubmitting(wrapper,isSubmitting){
  if(!wrapper)return;
  wrapper.classList.toggle('stockbeacon-form-wrapper--submitting',!!isSubmitting);
  var email=wrapper.querySelector('.stockbeacon-email');
  var consent=wrapper.querySelector('.stockbeacon-consent-checkbox');
  var btn=wrapper.querySelector('.stockbeacon-submit');
  if(email)email.disabled=!!isSubmitting;
  if(consent)consent.disabled=!!isSubmitting;
  if(btn)btn.disabled=!!isSubmitting;
}

async function handleSubmit(e){
  var btn=e.target;
  var wrapper=btn.closest('.stockbeacon-form-wrapper');
  if(!wrapper)return;
  var emailInput=wrapper.querySelector('.stockbeacon-email');
  var consent=wrapper.querySelector('.stockbeacon-consent-checkbox');
  var email=(emailInput.value||'').trim();
  hideMessage(wrapper);
  if(!email||!email.includes('@'))return showMessage(wrapper,stockbeaconData.i18n.invalid_email,'error');
  if(consent&&!consent.checked)return showMessage(wrapper,stockbeaconData.i18n.consent_required,'error');

  setSubmitButtonSubmitting(btn);
  setFormSubmitting(wrapper,true);

  var body=new FormData();
  body.append('action','stockbeacon_subscribe');
  body.append('_wpnonce',stockbeaconData.nonce);
  body.append('email',email);
  body.append('product_id',wrapper.dataset.productId||'0');
  body.append('variation_id',wrapper.dataset.variationId||'0');
  if(consent)body.append('consent',consent.checked?'1':'0');
  try{
    var resp=await fetch(stockbeaconData.ajaxUrl,{method:'POST',body:body});
    var data=await resp.json();
    if(data.success){
      var msg=wrapper.querySelector('.stockbeacon-success-message');
      if(msg&&data.data&&data.data.message)msg.textContent=data.data.message;
      wrapper.querySelector('.stockbeacon-form').style.display='none';
      wrapper.querySelector('.stockbeacon-success').style.display='block';
      wrapper.classList.remove('stockbeacon-form-wrapper--submitting');
      if(stockbeaconData.redirectUrl){
        window.location.href=stockbeaconData.redirectUrl;
      }
    }else{
      showMessage(wrapper,data.data&&data.data.message||data.message||stockbeaconData.i18n.error,'error');
      setFormSubmitting(wrapper,false);
      setSubmitButtonIdle(btn);
    }
  }catch(_){
    showMessage(wrapper,stockbeaconData.i18n.error,'error');
    setFormSubmitting(wrapper,false);
    setSubmitButtonIdle(btn);
  }
}
