// Apply intl-tel-input to phone fields
add_action( 'wp_footer', 'freeio_phone_input_script' );
function freeio_phone_input_script() {
    ?>
    <script>
    document.addEventListener("DOMContentLoaded", function() {
        // Find all possible phone inputs (CMB2 might use "tel" or "text" type with "phone" name)
        const phoneFields = document.querySelectorAll('input[type="tel"], input[name*="phone"]');

        phoneFields.forEach(function(field) {
            if (typeof window.intlTelInput !== "undefined") {
                const iti = window.intlTelInput(field, {
                    initialCountry: "auto",
                    geoIpLookup: function(callback) {
                        fetch("https://ipapi.co/json")
                            .then(res => res.json())
                            .then(data => callback(data.country_code))
                            .catch(() => callback("us"));
                    },
                    separateDialCode: true,
                    preferredCountries: ["fr", "tn", "us", "gb"], // 👈 edit to your most used countries
                    utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.19/js/utils.min.js"
                });

                // Optional: always save full number with country code
                field.form?.addEventListener("submit", function() {
                    if (iti.isValidNumber()) {
                        field.value = iti.getNumber(); // e.g. +216 22 123 456
                    }
                });
            }
        });
    });
    </script>
    <style>
        .iti { width: 100%; } /* make field full width */
    </style>
    <?php
}
