(function() {
	'use strict';

	function ready(callback) {
		if (document.readyState === 'loading') {
			document.addEventListener('DOMContentLoaded', callback);
			return;
		}

		callback();
	}

	function setCookie(name, value, days) {
		var expires = '';
		var host = window.location.hostname;

		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			expires = '; expires=' + date.toUTCString();
		}

		document.cookie = name + '=' + (value || '') + expires + '; path=/; SameSite=Lax';
		document.cookie = name + '=' + (value || '') + expires + '; path=/; domain=' + host + '; SameSite=Lax';
		document.cookie = name + '=' + (value || '') + expires + '; path=/; domain=.' + host + '; SameSite=Lax';
	}

	function expireCookie(name) {
		var host = window.location.hostname;

		document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; max-age=0; path=/; SameSite=Lax';
		document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; max-age=0; path=/; domain=' + host + '; SameSite=Lax';
		document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; max-age=0; path=/; domain=.' + host + '; SameSite=Lax';
	}

	function persistLanguageChoice(lang) {
		expireCookie('teknotok_ait_language');
		expireCookie('teknotok_visitor_language');
		setCookie('teknotok_ait_language', lang, 365);
		setCookie('teknotok_visitor_language', lang, 365);
	}

	function getCookie(name) {
		var nameEQ = name + '=';
		var cookies = document.cookie.split(';');

		for (var i = 0; i < cookies.length; i++) {
			var cookie = cookies[i];
			while (cookie.charAt(0) === ' ') {
				cookie = cookie.substring(1);
			}
			if (cookie.indexOf(nameEQ) === 0) {
				return cookie.substring(nameEQ.length);
			}
		}

		return null;
	}

	function switcherData() {
		return window.teknotokAitSwitcher || {};
	}

	function escapeHtml(value) {
		var element = document.createElement('span');
		element.textContent = value || '';
		return element.innerHTML;
	}

	function formatPromptText(template, langName) {
		return (template || '').replace('%lang_name%', '<strong>' + escapeHtml(langName) + '</strong>');
	}

	function getBrowserLanguageCode(targets) {
		var browserLanguages = navigator.languages && navigator.languages.length ? navigator.languages : [navigator.language || navigator.userLanguage || ''];

		for (var i = 0; i < browserLanguages.length; i++) {
			var normalized = String(browserLanguages[i] || '').toLowerCase().replace('_', '-');
			var primary = normalized.split('-')[0];

			if (targets && targets[normalized]) {
				return normalized;
			}

			if (targets && targets[primary]) {
				return primary;
			}
		}

		return '';
	}

	function closeSwitchers() {
		document.querySelectorAll('.teknotok-ait-switcher-container.open').forEach(function(container) {
			setSwitcherOpen(container, false);
		});
	}

	function setSwitcherOpen(container, isOpen) {
		var trigger = container.querySelector('.teknotok-ait-selected-lang');

		container.classList.toggle('open', isOpen);
		if (trigger) {
			trigger.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
		}
	}

	function resetLanguageSearch(container) {
		var input = container.querySelector('.teknotok-ait-search-input');

		container.querySelectorAll('li[data-lang]').forEach(function(item) {
			item.style.display = '';
		});

		if (!input) {
			return;
		}

		input.value = '';
		window.setTimeout(function() {
			input.focus();
		}, 100);
	}

	function initSwitcherInteractions() {
		document.addEventListener('click', function(event) {
			var trigger = event.target.closest('.teknotok-ait-selected-lang');
			var languageItem = event.target.closest('.teknotok-ait-languages-dropdown li[data-lang]');

			if (trigger) {
				event.stopPropagation();
				var container = trigger.closest('.teknotok-ait-switcher-container');
				var willOpen = !container.classList.contains('open');

				document.querySelectorAll('.teknotok-ait-switcher-container').forEach(function(otherContainer) {
					if (otherContainer !== container) {
						setSwitcherOpen(otherContainer, false);
					}
				});

				setSwitcherOpen(container, willOpen);
				if (willOpen) {
					resetLanguageSearch(container);
				}
				return;
			}

			if (languageItem) {
				var selectedLang = languageItem.getAttribute('data-lang');
				var link = languageItem.querySelector('a');
				var href = link ? link.getAttribute('href') : '';
				var data = switcherData();
				var targetUrl = href;

				persistLanguageChoice(selectedLang);

				if (href) {
					event.preventDefault();
					if (data.urls && data.urls[selectedLang]) {
						targetUrl = data.urls[selectedLang];
					}
					window.location.href = targetUrl;
				}
				return;
			}

			if (!event.target.closest('.teknotok-ait-switcher-container')) {
				closeSwitchers();
			}
		});

		document.addEventListener('keydown', function(event) {
			var trigger = event.target.closest('.teknotok-ait-selected-lang');

			if (trigger && (event.key === 'Enter' || event.key === ' ')) {
				event.preventDefault();
				trigger.click();
				return;
			}

			if (event.key === 'Escape') {
				closeSwitchers();
			}
		});

		document.addEventListener('input', function(event) {
			if (!event.target.matches('.teknotok-ait-search-input')) {
				return;
			}

			var query = event.target.value.toLowerCase().trim();
			var dropdown = event.target.closest('.teknotok-ait-languages-dropdown');
			if (!dropdown) {
				return;
			}

			dropdown.querySelectorAll('li[data-lang]').forEach(function(item) {
				var term = (item.getAttribute('data-search-term') || '').toLowerCase();
				item.style.display = term.indexOf(query) !== -1 ? '' : 'none';
			});
		});
	}

	function initRedirectPrompt() {
		var prompt = document.getElementById('teknotok-ait-redirect-prompt');
		if (!prompt || getCookie('teknotok_ait_redirect_prompt') === 'dismissed') {
			return;
		}

		var targets;
		var prompts;
		var browserLang;

		try {
			targets = JSON.parse(prompt.getAttribute('data-targets') || '{}');
			prompts = JSON.parse(prompt.getAttribute('data-prompts') || '{}');
		} catch (error) {
			targets = {};
			prompts = {};
		}

		browserLang = getBrowserLanguageCode(targets);

		if (!targets || !targets[browserLang]) {
			return;
		}

		var langName = targets[browserLang];
		var promptData = prompts && prompts[browserLang] ? prompts[browserLang] : null;
		var textElement = prompt.querySelector('.teknotok-ait-banner-text');
		var switchButton = document.getElementById('teknotok-ait-btn-switch');
		var dismissButton = document.getElementById('teknotok-ait-btn-dismiss');

		if (promptData && textElement) {
			textElement.innerHTML = formatPromptText(promptData.text, langName);
			if (switchButton) {
				switchButton.textContent = promptData.switch;
			}
			if (dismissButton) {
				dismissButton.textContent = promptData.dismiss;
			}
		} else if (textElement) {
			textElement.innerHTML = formatPromptText(textElement.innerHTML, langName);
		}

		prompt.style.display = 'block';

		if (switchButton) {
			switchButton.addEventListener('click', function() {
				var data = switcherData();
				persistLanguageChoice(browserLang);
				setCookie('teknotok_ait_redirect_prompt', 'dismissed', 30);

				if (data.urls && data.urls[browserLang]) {
					window.location.href = data.urls[browserLang];
					return;
				}

				var url = new URL(window.location.href);
				url.searchParams.set('lang', browserLang);
				window.location.href = url.toString();
			});
		}

		if (dismissButton) {
			dismissButton.addEventListener('click', function() {
				setCookie('teknotok_ait_redirect_prompt', 'dismissed', 30);
				prompt.style.display = 'none';
			});
		}
	}

	var checkoutDisplayTranslations = {};
	var checkoutObserver = null;
	var checkoutTranslationScheduled = false;

	function recoverCheckoutTranslations() {
		if (Object.keys(checkoutDisplayTranslations).length) {
			return;
		}

		if (switcherData().checkoutTranslations) {
			checkoutDisplayTranslations = switcherData().checkoutTranslations;
			return;
		}

		Array.prototype.some.call(document.scripts, function(script) {
			var text = script.textContent || '';
			var match;

			if (text.indexOf('teknotokAitSwitcher') === -1 || text.indexOf('checkoutTranslations') === -1) {
				return false;
			}

			match = text.match(/var\s+teknotokAitSwitcher\s*=\s*(\{[\s\S]*?\});/);
			if (!match) {
				return false;
			}

			try {
				var data = JSON.parse(match[1]);
				if (data && data.checkoutTranslations) {
					checkoutDisplayTranslations = data.checkoutTranslations;
					return true;
				}
			} catch (error) {
				return false;
			}

			return false;
		});
	}

	function isCheckoutTranslationExcluded(element) {
		if (!element || element.nodeType !== 1) {
			return false;
		}

		return !!element.closest(
			'iframe, script, style, textarea, input, select, option, ' +
			'.notranslate, [translate="no"]'
		);
	}

	function applyCheckoutDisplayTranslations() {
		recoverCheckoutTranslations();

		var translations = checkoutDisplayTranslations;
		var sources = Object.keys(translations).filter(function(source) {
			return source && translations[source];
		});
		var scope = document.querySelector('.wc-block-checkout, .wc-block-cart');

		if (!sources.length || !scope) {
			return;
		}

		scope.querySelectorAll('[placeholder], [aria-label], [title], [alt]').forEach(function(element) {
			if (isCheckoutTranslationExcluded(element)) {
				return;
			}

			['placeholder', 'aria-label', 'title', 'alt'].forEach(function(attribute) {
				var value = element.getAttribute(attribute);
				if (value && translations[value]) {
					element.setAttribute(attribute, translations[value]);
				}
			});
		});

		var walker = document.createTreeWalker(scope, NodeFilter.SHOW_TEXT, {
			acceptNode: function(node) {
				var parent = node.parentElement;
				if (!parent || isCheckoutTranslationExcluded(parent)) {
					return NodeFilter.FILTER_REJECT;
				}
				return NodeFilter.FILTER_ACCEPT;
			}
		});

		while (walker.nextNode()) {
			var textNode = walker.currentNode;
			var updated = textNode.nodeValue;

			sources.forEach(function(source) {
				if (updated.indexOf(source) !== -1) {
					updated = updated.split(source).join(translations[source]);
				}
			});

			if (updated !== textNode.nodeValue) {
				textNode.nodeValue = updated;
			}
		}
	}

	function observeCheckoutTranslations() {
		if (!window.MutationObserver) {
			return;
		}

		var checkoutTarget = document.querySelector('.wc-block-checkout, .wc-block-cart');
		if (!checkoutTarget) {
			return;
		}

		checkoutObserver = new MutationObserver(scheduleCheckoutDisplayTranslations);
		checkoutObserver.observe(checkoutTarget, {
			attributes: true,
			childList: true,
			subtree: true
		});
	}

	function runCheckoutDisplayTranslations() {
		checkoutTranslationScheduled = false;

		if (checkoutObserver) {
			checkoutObserver.disconnect();
		}

		applyCheckoutDisplayTranslations();
		observeCheckoutTranslations();
	}

	function scheduleCheckoutDisplayTranslations() {
		if (checkoutTranslationScheduled) {
			return;
		}

		checkoutTranslationScheduled = true;
		window.setTimeout(runCheckoutDisplayTranslations, 100);
	}

	ready(function() {
		initSwitcherInteractions();
		initRedirectPrompt();
		applyCheckoutDisplayTranslations();
		observeCheckoutTranslations();
	});
})();
