/**
 * Teléfonos internacionales — instalador Flexia (intl-tel-input + sync GPS).
 */
(function (global) {
  'use strict';

  global._installPhoneItis = global._installPhoneItis || [];

  function guessCountryFromValue(val) {
    var s = (val || '').trim().replace(/\s+/g, '');
    if (s.charAt(0) !== '+') return null;
    if (s.indexOf('+52') === 0) return 'mx';
    if (s.indexOf('+1') === 0) return 'us';
    if (s.indexOf('+34') === 0) return 'es';
    if (s.indexOf('+33') === 0) return 'fr';
    if (s.indexOf('+44') === 0) return 'gb';
    if (s.indexOf('+49') === 0) return 'de';
    if (s.indexOf('+54') === 0) return 'ar';
    if (s.indexOf('+55') === 0) return 'br';
    if (s.indexOf('+56') === 0) return 'cl';
    if (s.indexOf('+57') === 0) return 'co';
    if (s.indexOf('+51') === 0) return 'pe';
    if (s.indexOf('+506') === 0) return 'cr';
    if (s.indexOf('+593') === 0) return 'ec';
    if (s.indexOf('+598') === 0) return 'uy';
    if (s.indexOf('+595') === 0) return 'py';
    if (s.indexOf('+591') === 0) return 'bo';
    if (s.indexOf('+502') === 0) return 'gt';
    if (s.indexOf('+503') === 0) return 'sv';
    if (s.indexOf('+504') === 0) return 'hn';
    if (s.indexOf('+505') === 0) return 'ni';
    if (s.indexOf('+507') === 0) return 'pa';
    if (s.indexOf('+509') === 0) return 'ht';
    if (s.indexOf('+53') === 0) return 'cu';
    if (s.indexOf('+58') === 0) return 've';
    return null;
  }

  function attachDialCountrySync(iti, el) {
    if (!iti || !el) return;
    var t = null;
    function run() {
      var iso = guessCountryFromValue(el.value);
      if (!iso) return;
      try {
        var cur = iti.getSelectedCountryData && iti.getSelectedCountryData();
        if (cur && cur.iso2 === iso) return;
      } catch (e) {}
      try {
        iti.setCountry(iso);
      } catch (e2) {}
    }
    el.addEventListener('input', function () {
      if (t) clearTimeout(t);
      t = setTimeout(run, 160);
    });
    el.addEventListener('blur', run);
  }

  function geoIpLookup(callback) {
    fetch('https://ipapi.co/json/')
      .then(function (res) {
        return res.json();
      })
      .then(function (data) {
        var c = data && data.country_code ? String(data.country_code).toLowerCase() : '';
        if (c.length === 2) callback(c);
        else throw new Error('no');
      })
      .catch(function () {
        var parts = (global.navigator && global.navigator.language ? global.navigator.language : 'es-MX').split('-');
        var cc = parts.length > 1 && parts[1].length === 2 ? parts[1].toLowerCase() : 'mx';
        callback(cc);
      });
  }

  function removeFromRegistry(iti) {
    var list = global._installPhoneItis;
    for (var i = list.length - 1; i >= 0; i--) {
      if (list[i] === iti) list.splice(i, 1);
    }
  }

  function destroyPhoneInput(el) {
    if (!el) return;
    var iti = el._installPhoneIti;
    if (iti) {
      try {
        iti.destroy();
      } catch (e) {}
      removeFromRegistry(iti);
      el._installPhoneIti = null;
    }
    el.removeAttribute('data-install-phone-inited');
  }

  function resolveIntlTelUtilsUrl() {
    if (global.ANTARA_VENDOR && global.ANTARA_VENDOR.intlTelUtils) {
      return global.ANTARA_VENDOR.intlTelUtils;
    }
    var scripts = document.getElementsByTagName('script');
    var i;
    for (i = scripts.length - 1; i >= 0; i--) {
      var src = scripts[i].src || '';
      if (src.indexOf('install_phone.js') === -1) continue;
      try {
        var u = new URL(src);
        return u.origin + u.pathname.replace(/\/assets\/js\/install_phone\.js.*$/, '')
          + '/assets/vendor/intl-tel-input/23.0.6/js/utils.js';
      } catch (e) {
        break;
      }
    }
    return '/assets/vendor/intl-tel-input/23.0.6/js/utils.js';
  }

  function initPhoneInput(el, options) {
    options = options || {};
    if (!el || el.disabled) return null;
    if (el.getAttribute('data-install-phone-inited') === '1' && el._installPhoneIti) {
      return el._installPhoneIti;
    }
    if (typeof global.intlTelInput !== 'function') return null;
    destroyPhoneInput(el);
    var iti = global.intlTelInput(el, {
      loadUtilsOnInit: resolveIntlTelUtilsUrl(),
      dropdownContainer: document.body,
      initialCountry: options.initialCountry || 'auto',
      geoIpLookup: options.geoIpLookup !== false ? geoIpLookup : undefined,
      nationalMode: false,
      strictMode: false,
      formatOnDisplay: true,
      containerClass: 'iti-install-wrap',
    });
    attachDialCountrySync(iti, el);
    el._installPhoneIti = iti;
    el.setAttribute('data-install-phone-inited', '1');
    global._installPhoneItis.push(iti);
    if (options.countryCode) {
      try {
        iti.setCountry(String(options.countryCode).toLowerCase());
      } catch (e2) {}
    }
    return iti;
  }

  function syncAllPhones() {
    global._installPhoneItis.forEach(function (iti) {
      try {
        var el = iti.telInput || (iti.getInputElement && iti.getInputElement());
        if (!el || el.disabled) return;
        var full = iti.getNumber();
        if (full) el.value = full;
      } catch (e) {}
    });
  }

  document.addEventListener('install-geo-country', function (ev) {
    var detail = (ev && ev.detail) || {};
    var iso = (detail.countryCode || '').toLowerCase();
    if (iso.length !== 2) return;
    global._installPhoneItis.forEach(function (iti) {
      try {
        var el = iti.telInput || (iti.getInputElement && iti.getInputElement());
        if (!el || el.disabled) return;
        iti.setCountry(iso);
      } catch (e) {}
    });
  });

  global.InstallPhone = {
    init: initPhoneInput,
    destroy: destroyPhoneInput,
    syncAll: syncAllPhones,
    guessCountryFromValue: guessCountryFromValue,
  };
})(typeof window !== 'undefined' ? window : globalThis);
