var lkdm_callback_settings = {};

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + encodeURI(cvalue) + ";" + expires + ";path=/";
}
	
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return decodeURI(c.substring(name.length, c.length));
        }
    }
    return "";
}
function loadScript(src, callback) {
    let script = document.createElement('script');
    script.src = src;
    script.onload = () => callback();
    document.head.appendChild(script);
}
function isValidPhoneNumberByMask(phone, mask) {
    var regex = mask.replace(/\d/g, '\\d').replace(/[()+\-\s]/g, '\\$&');
    var pattern = new RegExp('^' + regex + '$');
    return pattern.test(phone);
}function applyMask(input, mask) {
			input.removeEventListener('input', input._maskHandler);

			input._maskHandler = function(e) {
				lkdm_callback_widget_shadow.shadowRoot.querySelector("input[name='phone']").classList.remove("lkdm_validate_error");
				var value = e.target.value.replace(/\D/g, ''); 
				var maskedValue = "";
				for (var i = 0, j = 0; i < mask.length && j < value.length; i++) {
					if (mask[i] === "0") {
						maskedValue += value[j];
						j++;
					} else {
						maskedValue += mask[i];
					}
				}
				e.target.value = maskedValue;
			};

			input.addEventListener('input', input._maskHandler);
		}
document.addEventListener('DOMContentLoaded', function() {
    var scripts = document.querySelectorAll('script[data-key]');
    var myScript = scripts[scripts.length - 1];

    if (myScript) {
        var widgetKey = myScript.getAttribute('data-key');
        //console.log("Widget Key: ", widgetKey);

        fetch("https://app.allwidgets.ru/s/callback/legacy.php?key=" + encodeURIComponent(widgetKey))
        .then(response => response.json())
        .then(data => {
            lkdm_callback_settings = data;
            //console.log(lkdm_callback_settings);
            loadScript('https://app.allwidgets.ru/s/callback/vendor/intl-tel-input/js/intlTelInput.js', function() {
                // После загрузки скрипта инициализируем виджет
                initializeWidget();
            });
        })
        .catch(error => console.error('Ошибка:', error));
    } else {
        console.error("Script tag with 'data-key' attribute not found.");
    }
});

function initializeWidget() {
    if (getCookie('start_url') == '') {
        setCookie('start_url', window.location.href, 1);
    }
    if (getCookie('start_url_title') == '') {
        setCookie('start_url_title', document.title, 1);
    }
    if (getCookie('referer') == '') {
        setCookie('referer', document.referrer, 1);
    }
    
	var referer = getCookie('referer');
var start_url = getCookie('start_url');
var start_url_title = getCookie('start_url_title');
var order_url = window.location.href;
var order_url_title = document.title;
var user_agent = window.navigator.userAgent;

    var lkdm_callback_widget_shadow = document.createElement('div');
	lkdm_callback_widget_shadow.style.display = "none";
    lkdm_callback_widget_shadow.style.position = "fixed";
    lkdm_callback_widget_shadow.style.zIndex = "999998";
    lkdm_callback_widget_shadow.style.bottom = "20px";
    lkdm_callback_widget_shadow.className = "lkdm_callback_widget_shadow";
    lkdm_callback_widget_shadow.attachShadow({mode: 'open'});
    lkdm_callback_widget_shadow.shadowRoot.innerHTML = lkdm_callback_settings.html;
    document.body.appendChild(lkdm_callback_widget_shadow);
    
    let lkdm_flag_script = document.createElement('script');
    lkdm_flag_script.src = 'https://app.allwidgets.ru/s/callback/vendor/intl-tel-input/js/intlTelInput.js';
    document.head.appendChild(lkdm_flag_script);
    
	const optionsJSON = {
		"position": "right",
		"mob_invert": false,
		"color": "#0acbd7"
	}

	function callbackWidget(data) {
		const container = lkdm_callback_widget_shadow.shadowRoot.querySelector("[data-widget-call]")
		const colorPrimary = data.color
		const mobInvert = data.mob_invert
		const buttonPosition = data.position

		if (colorPrimary) {
			container.style.setProperty("--color-primary", colorPrimary);
		}
		
		if(mobInvert) {
			lkdm_callback_widget_shadow.shadowRoot.querySelector("[data-callback-sticky]").classList.add("-lt-inverse-")
		}
		
		if (buttonPosition === "left") {
			lkdm_callback_widget_shadow.shadowRoot.querySelector("[data-callback-wrapper]").classList.add("-inverse-")
		}
	}

	function initPhoneInput(inputSelector) {
		var input = lkdm_callback_widget_shadow.shadowRoot.querySelector(inputSelector);
		var iti = window.intlTelInput(input, {
			preferredCountries: false,
			initialCountry: "auto",
			geoIpLookup: callback => {
				fetch("https://ipapi.co/json")
				.then(res => res.json())
				.then(data => callback(data.country_code))
				.catch(() => callback(lkdm_callback_settings.county));
			},
			initialCountry: lkdm_callback_settings.county,
			utilsScript: "https://app.allwidgets.ru/s/callback/vendor/intl-tel-input/js/utils.js",
		});
		
		iti.promise.then(function() {
			var countryNames = lkdm_callback_widget_shadow.shadowRoot.querySelectorAll('.iti__country-name');
			countryNames.forEach(function(nameElement) {
				var fullText = nameElement.innerText;
				var localName = fullText.split("(")[1];
				if (localName) {
					nameElement.innerText = localName.replace(")", "").trim();
				}
			});
			
			var initialPlaceholder = input.placeholder;
			var initialMask = placeholderToMask(initialPlaceholder);
			applyMask(input, initialMask);
		});
		

		function placeholderToMask(placeholder) {
			return placeholder.replace(/\d/g, '0');
		}

		function applyMask(input, mask) {
			input.removeEventListener('input', input._maskHandler);

			input._maskHandler = function(e) {
				lkdm_callback_widget_shadow.shadowRoot.querySelector("input[name='phone']").classList.remove("lkdm_validate_error");
				var value = e.target.value.replace(/\D/g, ''); 
				var maskedValue = "";
				for (var i = 0, j = 0; i < mask.length && j < value.length; i++) {
					if (mask[i] === "0") {
						maskedValue += value[j];
						j++;
					} else {
						maskedValue += mask[i];
					}
				}
				e.target.value = maskedValue;
			};

			input.addEventListener('input', input._maskHandler);
		}

		input.addEventListener('countrychange', function() {
			var placeholder = input.placeholder;
			var mask = placeholderToMask(placeholder);
			applyMask(input, mask);
			input.value = '';
		});
		

		var initialPlaceholder = "8 (912) 345-67-89";
		var initialMask = placeholderToMask(initialPlaceholder);
		applyMask(input, initialMask);
	}
	
	lkdm_callback_widget_shadow.shadowRoot.querySelector(".root").style.display = 'block';

    callbackWidget(optionsJSON)

    lkdm_callback_widget_shadow.shadowRoot.addEventListener("click", (event) => {
        if (event.target.closest("[data-callback-open]")) {
            event.target.closest("[data-callback]").classList.add("lt-xbutton-active")
        }
        if (event.target.closest("[data-callback-close]")) {
            event.target.closest("[data-callback]").classList.remove("lt-xbutton-active")
            event.target.closest("[data-callback]").classList.remove("lt-status-busy")
        }
        if (event.target.closest("[data-callback-show]")) {
            lkdm_callback_widget_shadow.shadowRoot.querySelector(".root").classList.add("-lt-callback-open-")
        }
        if (event.target.closest("[data-callback-hide]")) {
            lkdm_callback_widget_shadow.shadowRoot.querySelector(".root").classList.remove("-lt-callback-open-")
        }
        if (event.target.closest("[data-success-close]")) {
			lkdm_callback_widget_shadow.shadowRoot.querySelector(".lt-callback-success").style.opacity = 0;
			lkdm_callback_widget_shadow.shadowRoot.querySelector(".lt-callback-success").style.visibility = 'hidden';
			lkdm_callback_widget_shadow.shadowRoot.querySelector(".root").classList.remove("-lt-callback-open-");
        }
		
        if (event.target.closest("[data-widget-send]")) {
			var lkdm_elem_2_step = event.target.closest("[data-callback]");
			
			var phone = lkdm_callback_widget_shadow.shadowRoot.querySelector(".lkdm_phone").value;
			var mask = lkdm_callback_widget_shadow.shadowRoot.querySelector(".lkdm_phone").placeholder;
			var http = new XMLHttpRequest();
			var url = 'https://app.allwidgets.ru/s/callback/submit/index.php';
			var params = 'uuid=' + lkdm_callback_settings.uuid + '&phone=' + phone + '&referer=' + referer + '&start_url=' + start_url + '&start_url_title=' + start_url_title + '&order_url_title=' + order_url_title;
			
			if (!isValidPhoneNumberByMask(phone, mask)) {
                lkdm_callback_widget_shadow.shadowRoot.querySelector(".lkdm_phone").classList.add("lkdm_validate_error");
            } else {
    			http.open('POST', url, true);
    			http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    			http.onreadystatechange = function() {
    				if(http.readyState == 4 && http.status == 200 && http.responseText == 'ok') {
    					lkdm_callback_widget_shadow.shadowRoot.querySelector(".lt-xbutton-status-busy-txt-h1").innerHTML = lkdm_callback_settings.t_success_title;
    					lkdm_callback_widget_shadow.shadowRoot.querySelector(".lt-xbutton-status-busy-txt-p").innerHTML = lkdm_callback_settings.t_success_message;
    				} else {
    					lkdm_callback_widget_shadow.shadowRoot.querySelector(".lt-xbutton-status-busy-txt-h1").innerHTML = 'При отправке заявки произошла ошибка';
    					lkdm_callback_widget_shadow.shadowRoot.querySelector(".lt-xbutton-status-busy-txt-p").innerHTML = 'Пожалуйста, попробуйте позже';
    				}
    				
    				lkdm_elem_2_step.classList.add("lt-status-busy")
    			}
    			http.send(params);
    			
    			if (lkdm_callback_settings.metrika == 1){
    				if (typeof ym !== "undefined"){
    					ym(lkdm_callback_settings.ym_counter, "reachGoal", "aw_callback");
    				}
    			}
    			
    			if (lkdm_callback_settings.google_analytics == 1){
    				if (typeof gtag !== "undefined"){
    					gtag("event", "aw_callback");
    				}
    			}
    		}
        }
		
		if (event.target.closest("[data-callback-send-2]")) {
			var phone = lkdm_callback_widget_shadow.shadowRoot.querySelector(".lkdm_phone2 ").value;
			var mask = lkdm_callback_widget_shadow.shadowRoot.querySelector(".lkdm_phone").placeholder;
			var http = new XMLHttpRequest();
			var url = 'https://app.allwidgets.ru/s/callback/submit/index.php';
			var params = 'uuid=' + lkdm_callback_settings.uuid + '&phone=' + phone + '&referer=' + referer + '&start_url=' + start_url + '&start_url_title=' + start_url_title + '&order_url_title=' + order_url_title;
			
			if (!isValidPhoneNumberByMask(phone, mask)) {
                lkdm_callback_widget_shadow.shadowRoot.querySelector(".lkdm_phone").classList.add("lkdm_validate_error");
            } else {
    			http.open('POST', url, true);
    			http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    			http.onreadystatechange = function() {
    				if(http.readyState == 4 && http.status == 200 && http.responseText == 'ok') {
    					lkdm_callback_widget_shadow.shadowRoot.querySelector(".lt-callback-success .lt-callback-title").innerHTML = lkdm_callback_settings.t_success_title;
    					lkdm_callback_widget_shadow.shadowRoot.querySelector(".lt-callback-success .lt-callback-text ").innerHTML = lkdm_callback_settings.t_success_message;
    				} else {
    					lkdm_callback_widget_shadow.shadowRoot.querySelector(".lt-callback-success .lt-callback-title").innerHTML = 'При отправке заявки произошла ошибка';
    					lkdm_callback_widget_shadow.shadowRoot.querySelector(".lt-callback-success .lt-callback-text ").innerHTML = 'Пожалуйста, попробуйте позже';
    				}
    				
    				lkdm_callback_widget_shadow.shadowRoot.querySelector(".lt-callback-success").style.opacity = 1;
    				lkdm_callback_widget_shadow.shadowRoot.querySelector(".lt-callback-success").style.visibility = 'visible';
    			}
    			http.send(params);
    			
    			if (lkdm_callback_settings.metrika == 1){
    				if (typeof ym !== "undefined"){
    					ym(lkdm_callback_settings.ym_counter, "reachGoal", "aw_callback");
    				}
    			}
    			
    			if (lkdm_callback_settings.google_analytics == 1){
    				if (typeof gtag !== "undefined"){
    					gtag("event", "aw_callback");
    				}
    			}
    		}
        }
    })

    lkdm_callback_widget_shadow.shadowRoot.addEventListener("click", (event) => {
        if (event.target.closest("[data-callback-send]")) {
            lkdm_callback_widget_shadow.shadowRoot.querySelector("body").classList.remove("-lt-callback-open-")
            lkdm_callback_widget_shadow.shadowRoot.querySelector("body").classList.add("-lt-success-open-")
        }
    })
	
	initPhoneInput(".lkdm_phone");
    initPhoneInput(".lkdm_phone2");

	window.onload = function() {
		lkdm_callback_widget_shadow.style.display = "block";
	};
	
	setTimeout(() => lkdm_callback_widget_shadow.style.display = "block", 2000);
}

