(function() {
    'use strict';
    function initPhoneFormatting() {
        var phoneInput = document.querySelector('input[name="billing_phone"]');
        if (!phoneInput) {
            return;
        }
        phoneInput.addEventListener("focus", function () {
            if (phoneInput.value.trim() === "" || phoneInput.value === "+90") {
                phoneInput.value = "+90 ";
            }
        });
        phoneInput.addEventListener("input", function (event) {
            var numbers = phoneInput.value.replace(/\D/g, ""); 
            if (numbers.startsWith("90")) {
                numbers = numbers.substring(2); 
            }
            if (numbers.length > 10) {
                numbers = numbers.slice(0, 10); 
            }
            var firstDigit = numbers.charAt(0);
            if (numbers.length > 0 && !["2", "3", "4", "5", "8"].includes(firstDigit)) {
                numbers = ""; 
            }
            var formattedNumber = "+90";
            if (numbers.length > 0) formattedNumber += " (" + numbers.substring(0, 3);
            if (numbers.length > 3) formattedNumber += ") " + numbers.substring(3, 6);
            if (numbers.length > 6) formattedNumber += " " + numbers.substring(6, 8);
            if (numbers.length > 8) formattedNumber += " " + numbers.substring(8, 10);
            phoneInput.value = formattedNumber;
        });
        phoneInput.addEventListener("keydown", function (event) {
            if (event.key === "Backspace") {
                var currentValue = phoneInput.value;
                if (currentValue === "+90 ") {
                    event.preventDefault();
                }
            }
        });
        function addFormListener(formSelector) {
            var form = document.querySelector(formSelector);
            if (form) {
                form.addEventListener("submit", function (event) {
                    var numbers = phoneInput.value.replace(/\D/g, "").substring(2); 
                    if (numbers.length !== 10) {
                        phoneInput.value = ""; 
                    }
                });
            }
        }
        addFormListener("form"); 
        addFormListener("form.checkout"); 
    }
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initPhoneFormatting);
    } else {
        initPhoneFormatting();
    }
})();