(function(){
  function $(sel){ return document.querySelector(sel); }
  function ensureHidden(form){
    var hidden = form.querySelector('#billing_phone_e164');
    if(!hidden){
      hidden = document.createElement('input');
      hidden.type = 'hidden';
      hidden.name = 'billing_phone_e164';
      hidden.id   = 'billing_phone_e164';
      form.appendChild(hidden);
    }
    return hidden;
  }
  var form = document.querySelector('.checkout form, form#js-checkout-form, form#customer-form, form[action*="order"]') || document.forms[0];
  var phone = document.querySelector('input[type="tel"], input[name*="phone"], input[name="phone"]');
  if(!form || !phone){ return; }
  var countrySel = document.querySelector('select[name*="id_country"], select[name*="country"]');
  var hidden = ensureHidden(form);

  function init(){
    if(!window.intlTelInput){ return; }
    try{
      var initial = 'es';
      if(countrySel){
        var val = (countrySel.value||'').toString().toLowerCase();
        if(val.length===2){ initial = val; }
      }
      var iti = window.intlTelInput(phone, {
        initialCountry: initial,
        separateDialCode: true,
        nationalMode: true,
        utilsScript: 'https://cdn.jsdelivr.net/npm/intl-tel-input@19.5.8/build/js/utils.js'
      });
      if(countrySel){
        countrySel.addEventListener('change', function(){
          try{ iti.setCountry((countrySel.value||'').toLowerCase()); }catch(e){}
        });
      }
      form.addEventListener('submit', function(){
        try { hidden.value = iti.getNumber(); } catch(e){}
        if(!hidden.value){
          var raw = (phone.value||'').replace(/\D+/g,'');
          if(raw){ hidden.value = '+' + raw; }
        }
      });
    }catch(e){}
  }

  function loadCDNAndInit(){
    if(window.intlTelInput){ init(); return; }
    var link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = 'https://cdn.jsdelivr.net/npm/intl-tel-input@19.5.8/build/css/intlTelInput.css';
    document.head.appendChild(link);
    var s = document.createElement('script');
    s.src = 'https://cdn.jsdelivr.net/npm/intl-tel-input@19.5.8/build/js/intlTelInput.min.js';
    s.onload = init;
    document.head.appendChild(s);
  }

  if(window.intlTelInput){ init(); } else { loadCDNAndInit(); }
})();