/**
 * tnt_international_phone enhancements
 * - auto-select the phone widget's country/dial code from the address country field
 * - as-you-type formatting via libphonenumber-js (if bundled lib is loaded)
 *
 * Runs after functions.js (widget init) — resource priorities are ordered DESC.
 */
$(function () {
    'use strict';

    if (typeof pluginConfig === 'undefined') {
        return;
    }

    /* input selector => id used in the widget's element ids (tnt_waapi_dd_<name>) */
    var phoneFields = [
        { input: '#tel', widget: 'tel', scope: 'billing' },
        { input: '#mobile', widget: 'mobil', scope: 'billing' },
        { input: '#register-shipping_address-tel', widget: 'register-shipping_address-tel', scope: 'shipping' },
        { input: '#register-shipping_address-mobil', widget: 'register-shipping_address-mobil', scope: 'shipping' }
    ];
    var countrySelects = {
        billing: 'select[name="land"]',
        shipping: 'select[name="register[shipping_address][land]"]'
    };

    function isEmptyOrDialCodeOnly(value) {
        var v = String(value || '').trim();
        return v === '' || /^\+\d{0,4}$/.test(v);
    }

    /* ---- feature: auto-country from selected address country ---- */
    function applyCountry(scope) {
        var select = $(countrySelects[scope]);
        if (!select.length) {
            return;
        }
        var iso = String(select.val() || '').toLowerCase();
        if (iso === '') {
            return;
        }
        phoneFields.forEach(function (f) {
            if (f.scope !== scope) {
                return;
            }
            var input = $(f.input);
            if (!input.length || !isEmptyOrDialCodeOnly(input.val())) {
                return;
            }
            var item = $('#tnt_waapi_dd_' + f.widget + " .dropdown-menu a.dropdown-item[href='#" + iso + "']");
            if (item.length) {
                item.trigger('click');
                input.blur();
            }
        });
    }

    Object.keys(countrySelects).forEach(function (scope) {
        var select = $(countrySelects[scope]);
        if (!select.length) {
            return;
        }
        select.on('change', function () {
            applyCountry(scope);
        });
        applyCountry(scope);
    });

    /* ---- feature: as-you-type formatting (needs bundled libphonenumber-js) ---- */
    if (typeof libphonenumber !== 'undefined' && typeof libphonenumber.AsYouType === 'function') {
        var defaultCountry = String(pluginConfig.tnt_ip_default || 'de').toUpperCase();

        phoneFields.forEach(function (f) {
            var input = $(f.input);
            if (!input.length) {
                return;
            }
            input.on('input', function () {
                var el      = this;
                var raw     = el.value;
                var digits  = raw.replace(/[^\d+]/g, '');
                if (digits.length < 3 || /[^\d+()\/\s-]/.test(raw)) {
                    return; // too short or contains letters: leave untouched
                }
                var select  = $(countrySelects[f.scope]);
                var country = String(select.val() || '') !== ''
                    ? String(select.val()).toUpperCase()
                    : defaultCountry;
                var formatted = new libphonenumber.AsYouType(country).input(raw);
                if (formatted !== '' && formatted !== raw && el.selectionStart === raw.length) {
                    el.value = formatted;
                    el.dispatchEvent(new Event('keyup')); // keep flag detection in functions.js in sync
                }
            });
        });
    }
});
