(function(){
  'use strict';

  function setWhatsAppLink(){
    var a=document.getElementById('br-whatsapp-float');
    if(!a)return;
    var prefix=a.dataset.message||'مرحباً، أريد الاستفسار عن هذا المنتج:';
    var number=(a.dataset.number||'212660489317').replace(/[^0-9]/g,'');
    var msg=prefix+'\n'+document.title+'\n'+window.location.href;
    a.href='https://wa.me/'+number+'?text='+encodeURIComponent(msg);
  }

  function normalize(value){
    return String(value == null ? '' : value).trim().replace(/\s+/g,' ');
  }

  function setQuantity(qty, root){
    var scope=root||document;
    var input=scope.querySelector('.quantity-input, input[name="quantity"], input[type="number"]');
    if(!input)return;
    qty=parseInt(qty,10)||1;
    try{
      var desc=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value');
      if(desc&&desc.set) desc.set.call(input,qty); else input.value=qty;
    }catch(e){input.value=qty;}
    input.dispatchEvent(new Event('input',{bubbles:true}));
    input.dispatchEvent(new Event('change',{bubbles:true}));
  }

  function variationValues(variant){
    if(!variant || !variant.variations) return [];
    return Object.keys(variant.variations).map(function(k){return normalize(variant.variations[k]);});
  }

  function findVariantByOffer(value){
    if(typeof variants === 'undefined' || !Array.isArray(variants)) return null;
    value=normalize(value);
    return variants.find(function(v){ return variationValues(v).indexOf(value)!==-1; }) || null;
  }

  function selectNativeOption(root, value){
    var optionRoot=root.querySelector('.product-options');
    if(!optionRoot) return false;
    value=normalize(value);
    var matched=false;

    optionRoot.querySelectorAll('.product-option').forEach(function(option){
      var type=option.dataset.type;
      if(matched) return;

      if(type==='radio_buttons'){
        option.querySelectorAll('.yc-radio-buttons').forEach(function(label){
          var input=label.querySelector('input[type="radio"]');
          if(input && normalize(input.value)===value){
            option.querySelectorAll('.yc-radio-buttons').forEach(function(x){x.classList.remove('active');});
            label.classList.add('active');
            input.checked=true;
            input.dispatchEvent(new Event('change',{bubbles:true}));
            matched=true;
          }
        });
      } else if(type==='textual_buttons'){
        option.querySelectorAll('.yc-options-item').forEach(function(item){
          if(normalize(item.textContent)===value){
            option.querySelectorAll('.yc-options-item').forEach(function(x){x.classList.remove('active');});
            item.classList.add('active');
            matched=true;
          }
        });
      } else if(type==='dropdown'){
        option.querySelectorAll('.dropdown-content li').forEach(function(item){
          if(normalize(item.textContent)===value){
            option.querySelectorAll('.dropdown-content li').forEach(function(x){x.classList.remove('selected');});
            item.classList.add('selected');
            var label=option.querySelector('.option-name');
            if(label) label.textContent=item.textContent;
            matched=true;
          }
        });
      }
    });

    if(matched){
      // MutationObserver in product.js reads the active option and updates variant id, price and stock.
      optionRoot.setAttribute('data-br-selection', value + '-' + Date.now());
    }
    return matched;
  }

  function setOfferActive(box, value){
    value=normalize(value);
    box.querySelectorAll('.br-quantity-offer').forEach(function(btn){
      var active=normalize(btn.dataset.offerValue)===value;
      btn.classList.toggle('is-active',active);
      btn.setAttribute('aria-pressed',active?'true':'false');
    });
  }

  function selectedOfferValue(root){
    if(typeof getSelectedVariant==='function'){
      try{
        var v=getSelectedVariant(root);
        if(v){
          var values=variationValues(v);
          var box=root.querySelector('.br-quantity-offers');
          if(box){
            var names=Array.prototype.map.call(box.querySelectorAll('.br-quantity-offer'),function(b){return normalize(b.dataset.offerValue);});
            for(var i=0;i<values.length;i++) if(names.indexOf(values[i])!==-1) return values[i];
          }
        }
      }catch(e){}
    }
    return '';
  }

  function refreshOfferPrices(box){
    if(typeof variants==='undefined' || !Array.isArray(variants)) return;
    box.querySelectorAll('.br-quantity-offer').forEach(function(btn){
      var variant=findVariantByOffer(btn.dataset.offerValue);
      if(!variant) return;
      btn.dataset.variantId=variant.id || '';
      var priceEl=btn.querySelector('.br-quantity-offer__price');
      if(priceEl && variant.price != null && typeof formatCurrency==='function'){
        priceEl.textContent=formatCurrency(variant.price, CURRENCY_CODE, CUSTOMER_LOCALE);
      }
    });
  }

  function bindQuantityOffers(){
    document.querySelectorAll('.br-quantity-offers').forEach(function(box){
      if(box.dataset.bound==='1')return;
      box.dataset.bound='1';
      var productRoot=box.closest('.yc-single-product')||document;
      var offers=box.querySelectorAll('.br-quantity-offer');

      refreshOfferPrices(box);

      offers.forEach(function(btn){
        btn.addEventListener('click',function(){
          var offerValue=btn.dataset.offerValue || '';
          var variant=findVariantByOffer(offerValue);
          if(variant && selectNativeOption(productRoot,offerValue)){
            // The offer is itself a YouCan variant (1 piece / 2 pieces / 3 pieces), so cart quantity must stay 1.
            setQuantity(1,productRoot);
            setOfferActive(box,offerValue);
          } else {
            // Fallback for products without matching variants: behave as classic quantity offers.
            setQuantity(btn.dataset.qty,productRoot);
            setOfferActive(box,offerValue);
          }
        });
      });

      var initial=selectedOfferValue(productRoot);
      if(initial) setOfferActive(box,initial);
      else if(offers.length) offers[0].click();

      var nativeOptions=productRoot.querySelector('.product-options');
      if(nativeOptions){
        new MutationObserver(function(){
          refreshOfferPrices(box);
          var value=selectedOfferValue(productRoot);
          if(value) setOfferActive(box,value);
        }).observe(nativeOptions,{attributes:true,childList:true,subtree:true});
      }
    });
  }

  document.addEventListener('DOMContentLoaded',function(){setWhatsAppLink();bindQuantityOffers();});
})();
